Whamcloud - gitweb
LU-3365 lmv: support DNE with HSM.
[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         strncpy(info->link, link, PATH_MAX);
573         info->link[PATH_MAX] = '\0';
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
633         p = calloc(1, sizeof(*p));
634         if (!p)
635                 return -ENOMEM;
636         strcpy(p->pc_log.pcl_pfid, pfid);
637         strcpy(p->pc_log.pcl_tfid, tfid);
638         strcpy(p->pc_log.pcl_name, name);
639
640         p->pc_next = parents;
641         parents = p;
642         return 0;
643 }
644
645 void lr_cascade_move(const char *fid, const char *dest, struct lr_info *info)
646 {
647         struct lr_parent_child_list *curr, *prev;
648         char *d;
649         int rc;
650
651         d = calloc(1, PATH_MAX + 1);
652         prev = curr = parents;
653         while (curr) {
654                 if (strcmp(curr->pc_log.pcl_pfid, fid) == 0) {
655                         snprintf(d, PATH_MAX, "%s/%s", dest,
656                                  curr->pc_log.pcl_name);
657                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
658                                 status->ls_targets[info->target_no],
659                                 SPECIAL_DIR, curr->pc_log.pcl_tfid);
660                         rc = rename(info->src, d);
661                         if (rc == -1) {
662                                 fprintf(stderr, "Error renaming file "
663                                         " %s to %s: %d\n",
664                                         info->src, d, errno);
665                                 errors++;
666                         }
667                         lr_cascade_move(curr->pc_log.pcl_tfid, d, info);
668                         if (curr == parents)
669                                 parents = curr->pc_next;
670                         else
671                                 prev->pc_next = curr->pc_next;
672                         free(curr);
673                         prev = curr = parents;
674
675                 } else {
676                         prev = curr;
677                         curr = curr->pc_next;
678                 }
679         }
680
681         free(d);
682 }
683
684 /* remove [info->spfid, info->sfid] from parents */
685 int lr_remove_pc(const char *pfid, const char *tfid)
686 {
687         struct lr_parent_child_list *curr, *prev;
688
689         for (prev = curr = parents; curr; prev = curr, curr = curr->pc_next) {
690                 if (strcmp(curr->pc_log.pcl_pfid, pfid) == 0 &&
691                     strcmp(curr->pc_log.pcl_tfid, tfid) == 0) {
692                         if (curr == parents)
693                                 parents = curr->pc_next;
694                         else
695                                 prev->pc_next = curr->pc_next;
696                         free(curr);
697                         break;
698                 }
699         }
700         return 0;
701 }
702
703 /* Create file under SPECIAL_DIR with its tfid as its name. */
704 int lr_mk_special(struct lr_info *info)
705 {
706         int rc;
707
708         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
709                 status->ls_targets[info->target_no], SPECIAL_DIR,
710                 info->tfid);
711
712         rc = lr_mkfile(info);
713         if (rc)
714                 return rc;
715
716         rc = lr_add_pc(info->pfid, info->tfid, info->name);
717         return rc;
718 }
719
720 /* Remove a file or directory */
721 int lr_rmfile(struct lr_info *info)
722 {
723         int rc;
724
725         if (info->type == CL_RMDIR)
726                 rc = rmdir(info->dest);
727         else
728                 rc = unlink(info->dest);
729         if (rc == -1)
730                 rc = -errno;
731         return rc;
732 }
733
734 /* Recursively remove directory and its contents */
735 int lr_rm_recursive(struct lr_info *info)
736 {
737         int rc;
738
739         snprintf(info->cmd, PATH_MAX, "rm -rf %s", info->dest);
740         rc = system(info->cmd);
741         if (rc == -1)
742                 rc = -errno;
743
744         return rc;
745 }
746
747 /* Remove a file under SPECIAL_DIR with its tfid as its name. */
748 int lr_rm_special(struct lr_info *info)
749 {
750         int rc;
751
752         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
753                  status->ls_targets[info->target_no], SPECIAL_DIR,
754                  info->tfid);
755         rc = lr_rmfile(info);
756
757         if (rc)
758                 lr_debug(DINFO, "remove: %s; rc=%d, errno=%d\n",
759                          info->dest, rc, errno);
760         return rc;
761 }
762
763 /* Replicate file and directory create events */
764 int lr_create(struct lr_info *info)
765 {
766         int len;
767         int rc1 = 0;
768         int rc;
769         int mkspecial = 0;
770
771         /* Is target FID present on the source? */
772         rc = lr_get_path(info, info->tfid);
773         if (rc == -ENOENT) {
774                 /* Source file has disappeared. Not an error. */
775                 lr_debug(DINFO, "create: tfid %s not found on"
776                          "source-fs\n", info->tfid);
777                 return 0;
778         } else if (rc) {
779                 return rc;
780         }
781         strcpy(info->savedpath, info->path);
782
783         /* Is parent FID present on the source */
784         rc = lr_get_path(info, info->pfid);
785         if (rc == -ENOENT) {
786                 lr_debug(DINFO, "create: pfid %s not found on source-fs\n",
787                          info->tfid);
788                 mkspecial = 1;
789         } else if (rc < 0) {
790                 return rc;
791         }
792
793         /* Is f2p(pfid)+name != f2p(tfid)? If not the file has moved. */
794         len = strlen(info->path);
795         if (len == 1 && info->path[0] == '/')
796                 snprintf(info->dest, PATH_MAX, "%s", info->name);
797         else if (len - 1 > 0 && info->path[len - 1] == '/')
798                 snprintf(info->dest, PATH_MAX, "%s%s", info->path, info->name);
799         else
800                 snprintf(info->dest, PATH_MAX, "%s/%s", info->path, info->name);
801
802         lr_debug(DTRACE, "dest = %s; savedpath = %s\n", info->dest,
803                  info->savedpath);
804         if (strncmp(info->dest, info->savedpath, PATH_MAX) != 0) {
805                 lr_debug(DTRACE, "create: file moved (%s). %s != %s\n",
806                          info->tfid, info->dest, info->savedpath);
807                 mkspecial = 1;
808         }
809
810         /* Is f2p(pfid) present on the target? If not, the parent has
811            moved */
812         if (!mkspecial) {
813                 snprintf(info->dest, PATH_MAX, "%s/%s", status->ls_targets[0],
814                         info->path);
815                 if (access(info->dest, F_OK) != 0) {
816                         lr_debug(DTRACE, "create: parent %s not found\n",
817                                 info->dest);
818                         mkspecial = 1;
819                 }
820         }
821         for (info->target_no = 0; info->target_no < status->ls_num_targets;
822              info->target_no++) {
823                 snprintf(info->dest, PATH_MAX, "%s/%s",
824                         status->ls_targets[info->target_no], info->savedpath);
825                 lr_get_FID_PATH(status->ls_source, info->tfid, info->src,
826                                     PATH_MAX);
827
828                 if (!mkspecial)
829                         rc1 = lr_mkfile(info);
830                 if (mkspecial || rc1 == -ENOENT) {
831                         rc1 = lr_mk_special(info);
832                 }
833                 if (rc1)
834                         rc = rc1;
835         }
836         return rc;
837 }
838
839 /* Replicate a file remove (rmdir/unlink) operation */
840 int lr_remove(struct lr_info *info)
841 {
842         int rc = 0;
843         int rc1;
844
845         for (info->target_no = 0; info->target_no < status->ls_num_targets;
846              info->target_no++) {
847
848                 rc1 = lr_rm_special(info);
849                 if (!rc1)
850                         continue;
851
852                 rc1 = lr_get_path(info, info->pfid);
853                 if (rc1 == -ENOENT) {
854                         lr_debug(DINFO, "remove: pfid %s not found\n",
855                                  info->pfid);
856                         continue;
857                 }
858                 if (rc1) {
859                         rc = rc1;
860                         continue;
861                 }
862                 snprintf(info->dest, PATH_MAX, "%s/%s/%s",
863                         status->ls_targets[info->target_no], info->path,
864                         info->name);
865
866                 rc1 = lr_rmfile(info);
867                 lr_debug(DINFO, "remove: %s; rc1=%d, errno=%d\n",
868                          info->dest, rc1, errno);
869                 if (rc1 == -ENOTEMPTY)
870                         rc1 = lr_rm_recursive(info);
871
872                 if (rc1) {
873                         rc = rc1;
874                         continue;
875                 }
876         }
877         return rc;
878 }
879
880 /* Replicate a rename/move operation. */
881 int lr_move(struct lr_info *info)
882 {
883         int rc = 0;
884         int rc1;
885         int rc_dest, rc_src;
886         int special_src = 0;
887         int special_dest = 0;
888         char srcpath[PATH_MAX + 1] = "";
889
890         LASSERT(info->is_extended);
891
892         rc_src = lr_get_path(info, info->spfid);
893         if (rc_src < 0 && rc_src != -ENOENT)
894                 return rc_src;
895         memcpy(srcpath, info->path, strlen(info->path));
896
897         rc_dest = lr_get_path(info, info->pfid);
898         if (rc_dest < 0 && rc_dest != -ENOENT)
899                 return rc_dest;
900
901         for (info->target_no = 0; info->target_no < status->ls_num_targets;
902              info->target_no++) {
903
904                 if (!rc_dest) {
905                         snprintf(info->dest, PATH_MAX, "%s/%s",
906                                 status->ls_targets[info->target_no],
907                                 info->path);
908                         if (access(info->dest, F_OK) != 0) {
909                                 rc_dest = -errno;
910                         } else {
911                                 snprintf(info->dest, PATH_MAX, "%s/%s/%s",
912                                         status->ls_targets[info->target_no],
913                                         info->path, info->name);
914                         }
915                         lr_debug(DINFO, "dest path %s rc_dest=%d\n", info->dest,
916                                  rc_dest);
917                 }
918                 if (rc_dest == -ENOENT) {
919                         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
920                                 status->ls_targets[info->target_no],
921                                 SPECIAL_DIR, info->sfid);
922                         special_dest = 1;
923                         lr_debug(DINFO, "special dest %s\n", info->dest);
924                 }
925
926                 if (!rc_src) {
927                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
928                                 status->ls_targets[info->target_no],
929                                 srcpath, info->sname);
930                         lr_debug(DINFO, "src path %s rc_src=%d\n", info->src,
931                                  rc_src);
932                 }
933                 if (rc_src == -ENOENT || (access(info->src, F_OK) != 0 &&
934                                           errno == ENOENT)) {
935                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
936                                 status->ls_targets[info->target_no],
937                                 SPECIAL_DIR, info->sfid);
938                         special_src = 1;
939                         lr_debug(DINFO, "special src %s\n", info->src);
940                 }
941
942                 rc1 = 0;
943                 errno = 0;
944                 if (strcmp(info->src, info->dest) != 0) {
945                         rc1 = rename(info->src, info->dest);
946                         if (rc1 == -1)
947                                 rc1 = -errno;
948                         lr_debug(DINFO, "rename returns %d\n", rc1);
949                 }
950
951                 if (special_src) {
952                         rc1 = lr_remove_pc(info->spfid, info->sfid);
953                         if (!special_dest)
954                                 lr_cascade_move(info->sfid, info->dest, info);
955                 }
956                 if (special_dest)
957                         rc1 = lr_add_pc(info->pfid, info->sfid, info->name);
958
959                 lr_debug(DINFO, "move: %s [to] %s rc1=%d, errno=%d\n",
960                          info->src, info->dest, rc1, errno);
961                 if (rc1)
962                         rc = rc1;
963         }
964         return rc;
965 }
966
967 /* Replicate a hard link */
968 int lr_link(struct lr_info *info)
969 {
970         int i;
971         int len;
972         int rc;
973         int rc1;
974         struct stat st;
975
976         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
977         rc = stat(info->src, &st);
978         if (rc == -1)
979                 return -errno;
980
981         for (info->target_no = 0; info->target_no < status->ls_num_targets;
982              info->target_no++) {
983
984                 info->src[0] = 0;
985                 info->dest[0] = 0;
986                 rc1 = 0;
987
988                 /* Search through the hardlinks to get the src and dest */
989                 for (i = 0; i < st.st_nlink && (info->src[0] == 0 ||
990                                                 info->dest[0] == 0); i++) {
991                         rc1 = lr_get_path_ln(info, info->tfid, i);
992                         lr_debug(rc1 ? 0:DTRACE, "\tfid2path %s, %s, %d rc=%d\n",
993                                  info->path, info->name, i, rc1);
994                         if (rc1)
995                                 break;
996
997                         len = strlen(info->path) - strlen(info->name);
998                         if (len > 0 && strcmp(info->path + len,
999                                               info->name) == 0)
1000                                 snprintf(info->dest, PATH_MAX, "%s/%s",
1001                                         status->ls_targets[info->target_no],
1002                                         info->path);
1003                         else if (info->src[0] == 0)
1004                                 snprintf(info->src, PATH_MAX, "%s/%s",
1005                                         status->ls_targets[info->target_no],
1006                                         info->path);
1007                 }
1008
1009                 if (rc1) {
1010                         rc = rc1;
1011                         continue;
1012                 }
1013
1014                 if (info->src[0] == 0 || info->dest[0] == 0)
1015                         /* Could not find the source or destination.
1016                          This can happen when some links don't exist
1017                          anymore. */
1018                         return -EINVAL;
1019
1020                 if (info->src[0] == 0)
1021                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
1022                                 status->ls_targets[info->target_no],
1023                                 SPECIAL_DIR, info->tfid);
1024                 else if (info->dest[0] == 0)
1025                         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
1026                                 status->ls_targets[info->target_no],
1027                                 SPECIAL_DIR, info->tfid);
1028
1029                 rc1 = link(info->src, info->dest);
1030                 lr_debug(rc1?0:DINFO, "link: %s [to] %s; rc1=%d %s\n",
1031                          info->src, info->dest, rc1, strerror(errno));
1032
1033                 if (rc1)
1034                         rc = rc1;
1035         }
1036         return rc;
1037 }
1038
1039 /* Replicate file attributes */
1040 int lr_setattr(struct lr_info *info)
1041 {
1042         int rc1;
1043         int rc;
1044
1045         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
1046
1047         rc = lr_get_path(info, info->tfid);
1048         if (rc == -ENOENT)
1049                 lr_debug(DINFO, "setattr: %s not present on source-fs\n",
1050                          info->src);
1051         if (rc)
1052                 return rc;
1053
1054         for (info->target_no = 0; info->target_no < status->ls_num_targets;
1055              info->target_no++) {
1056
1057                 snprintf(info->dest, PATH_MAX, "%s/%s",
1058                          status->ls_targets[info->target_no], info->path);
1059                 lr_debug(DINFO, "setattr: %s %s %s", info->src, info->dest,
1060                          info->tfid);
1061
1062                 rc1 = lr_sync_data(info);
1063                 if (!rc1)
1064                         rc1 = lr_copy_attr(info->src, info->dest);
1065                 if (rc1)
1066                         rc = rc1;
1067         }
1068         return rc;
1069 }
1070
1071 /* Replicate xattrs */
1072 int lr_setxattr(struct lr_info *info)
1073 {
1074         int rc, rc1;
1075
1076         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
1077
1078         rc = lr_get_path(info, info->tfid);
1079         if (rc == -ENOENT)
1080                 lr_debug(DINFO, "setxattr: %s not present on source-fs\n",
1081                          info->src);
1082         if (rc)
1083                 return rc;
1084
1085         for (info->target_no = 0; info->target_no < status->ls_num_targets;
1086              info->target_no++) {
1087
1088                 snprintf(info->dest, PATH_MAX, "%s/%s",
1089                         status->ls_targets[info->target_no], info->path);
1090                 lr_debug(DINFO, "setxattr: %s %s %s\n", info->src, info->dest,
1091                          info->tfid);
1092
1093                 rc1 = lr_copy_xattr(info);
1094                 if (rc1)
1095                         rc = rc1;
1096         }
1097
1098         return rc;
1099 }
1100
1101 /* Parse a line of changelog entry */
1102 int lr_parse_line(void *priv, struct lr_info *info)
1103 {
1104         struct changelog_ext_rec *rec;
1105
1106         if (llapi_changelog_recv(priv, &rec) != 0)
1107                 return -1;
1108
1109         info->is_extended = CHANGELOG_REC_EXTENDED(rec);
1110         info->recno = rec->cr_index;
1111         info->type = rec->cr_type;
1112         sprintf(info->tfid, DFID, PFID(&rec->cr_tfid));
1113         sprintf(info->pfid, DFID, PFID(&rec->cr_pfid));
1114         strncpy(info->name, rec->cr_name, rec->cr_namelen);
1115
1116         if (fid_is_sane(&rec->cr_sfid)) {
1117                 sprintf(info->sfid, DFID, PFID(&rec->cr_sfid));
1118                 sprintf(info->spfid, DFID, PFID(&rec->cr_spfid));
1119                 strncpy(info->sname, changelog_rec_sname(rec),
1120                         changelog_rec_snamelen(rec));
1121                 info->sname[changelog_rec_snamelen(rec)] = '\0';
1122
1123                 if (verbose > 1)
1124                         printf("Rec %lld: %d %s %s\n", info->recno, info->type,
1125                                 info->name, info->sname);
1126         } else {
1127                 info->name[rec->cr_namelen] = '\0';
1128
1129                 if (verbose > 1)
1130                         printf("Rec %lld: %d %s\n", info->recno, info->type,
1131                                 info->name);
1132         }
1133
1134         llapi_changelog_free(&rec);
1135
1136         rec_count++;
1137         return 0;
1138 }
1139
1140 /* Initialize the replication parameters */
1141 int lr_init_status()
1142 {
1143         size_t size = sizeof(struct lustre_rsync_status) + PATH_MAX + 1;
1144
1145         if (status != NULL)
1146                 return 0;
1147         status = calloc(size, 1);
1148         if (status == NULL)
1149                 return -ENOMEM;
1150         status->ls_version = REPLICATE_STATUS_VER;
1151         status->ls_size = size;
1152         status->ls_last_recno = -1;
1153         return 0;
1154 }
1155
1156 /* Make a backup of the statuslog */
1157 void lr_backup_log()
1158 {
1159         char backupfile[PATH_MAX];
1160
1161         if (logbackedup)
1162                 return;
1163         snprintf(backupfile, PATH_MAX, "%s.old", statuslog);
1164         (void) rename(statuslog, backupfile);
1165         logbackedup = 1;
1166
1167         return;
1168 }
1169
1170 /* Save replication parameters to a statuslog. */
1171 int lr_write_log()
1172 {
1173         int fd;
1174         size_t size;
1175         size_t write_size = status->ls_size;
1176         struct lr_parent_child_list *curr;
1177         int rc = 0;
1178
1179         if (statuslog == NULL)
1180                 return 0;
1181
1182         lr_backup_log();
1183
1184         fd = open(statuslog, O_WRONLY | O_CREAT | O_SYNC,
1185                              S_IRUSR | S_IWUSR);
1186         if (fd == -1) {
1187                 fprintf(stderr, "Error opening log file for writing (%s)\n",
1188                         statuslog);
1189                 return -1;
1190         }
1191         errno = 0;
1192         size = write(fd, status, write_size);
1193         if (size != write_size) {
1194                 fprintf(stderr, "Error writing to log file (%s) %d\n",
1195                         statuslog, errno);
1196                 close(fd);
1197                 return -1;
1198         }
1199
1200         for (curr = parents; curr; curr = curr->pc_next) {
1201                 size = write(fd, &curr->pc_log, sizeof(curr->pc_log));
1202                 if (size != sizeof(curr->pc_log)) {
1203                         fprintf(stderr, "Error writing to log file (%s) %d\n",
1204                                 statuslog, errno);
1205                         rc = -1;
1206                         break;
1207                 }
1208         }
1209         close(fd);
1210         return rc;
1211 }
1212
1213 /* Read statuslog and populate the replication parameters.  Command
1214  * line parameters take precedence over parameters in the log file.*/
1215 int lr_read_log()
1216 {
1217         struct lr_parent_child_list *tmp;
1218         struct lr_parent_child_log rec;
1219         struct lustre_rsync_status *s;
1220         int fd = -1;
1221         size_t size;
1222         size_t read_size = sizeof(struct lustre_rsync_status) + PATH_MAX + 1;
1223         int rc = 0;
1224
1225         if (statuslog == NULL)
1226                 return 0;
1227
1228         s = calloc(1, read_size);
1229         if (s == NULL)
1230                 GOTO(out, rc = -ENOMEM);
1231
1232         fd = open(statuslog, O_RDONLY);
1233         if (fd == -1)
1234                 GOTO(out, rc = -errno);
1235         size = read(fd, s, read_size);
1236         if (size != read_size)
1237                 GOTO(out, rc = -EINVAL);
1238         if (read_size < s->ls_size) {
1239                 read_size = s->ls_size;
1240                 s = lr_grow_buf(s, read_size);
1241                 if (s == NULL)
1242                         GOTO(out, rc = -ENOMEM);
1243                 if (lseek(fd, 0, SEEK_SET) == -1)
1244                         GOTO(out, rc = -errno);
1245                 size = read(fd, s, read_size);
1246                 if (size != read_size)
1247                         GOTO(out, rc = -EINVAL);
1248         }
1249
1250         while (read(fd, &rec, sizeof(rec)) != 0) {
1251                 tmp = calloc(1, sizeof(*tmp));
1252                 if (!tmp)
1253                         GOTO(out, rc = -ENOMEM);
1254                 tmp->pc_log = rec;
1255                 tmp->pc_next = parents;
1256                 parents = tmp;
1257         }
1258
1259         /* copy uninitialized fields to status */
1260         if (status->ls_num_targets == 0) {
1261                 if (status->ls_size != s->ls_size) {
1262                         status = lr_grow_buf(status, s->ls_size);
1263                         if (status == NULL)
1264                                 GOTO(out, rc = -ENOMEM);
1265                         status->ls_size = s->ls_size;
1266                 }
1267                 status->ls_num_targets = s->ls_num_targets;
1268                 memcpy(status->ls_targets, s->ls_targets,
1269                        (PATH_MAX + 1) * s->ls_num_targets);
1270         }
1271         if (status->ls_last_recno == -1)
1272                 status->ls_last_recno = s->ls_last_recno;
1273
1274         if (status->ls_registration[0] == '\0')
1275                 strncpy(status->ls_registration, s->ls_registration,
1276                         LR_NAME_MAXLEN);
1277
1278         if (status->ls_mdt_device[0] == '\0')
1279                 strncpy(status->ls_mdt_device, s->ls_mdt_device,
1280                         LR_NAME_MAXLEN);
1281
1282         if (status->ls_source_fs[0] == '\0')
1283                 strncpy(status->ls_source_fs, s->ls_source_fs,
1284                         LR_NAME_MAXLEN);
1285
1286         if (status->ls_source[0] == '\0')
1287                 strncpy(status->ls_source, s->ls_source, PATH_MAX);
1288
1289  out:
1290         if (fd != -1)
1291                 close(fd);
1292         if (s)
1293                 free(s);
1294         return rc;
1295 }
1296
1297 /* Clear changelogs every CLEAR_INTERVAL records or at the end of
1298    processing. */
1299 int lr_clear_cl(struct lr_info *info, int force)
1300 {
1301         char    mdt_device[LR_NAME_MAXLEN + 1];
1302         long long rec;
1303         int rc = 0;
1304
1305         if (force || info->recno > status->ls_last_recno + CLEAR_INTERVAL) {
1306                 if (info->type == CL_RENAME)
1307                         rec = info->recno + 1;
1308                 else
1309                         rec = info->recno;
1310                 if (!noclear && !dryrun) {
1311                         /* llapi_changelog_clear modifies the mdt
1312                          * device name so make a copy of it until this
1313                          * is fixed.
1314                         */
1315                         strncpy(mdt_device, status->ls_mdt_device,
1316                                 LR_NAME_MAXLEN);
1317                         rc = llapi_changelog_clear(mdt_device,
1318                                                    status->ls_registration,
1319                                                    rec);
1320                         if (rc)
1321                                 printf("Changelog clear (%s, %s, %lld) "
1322                                        "returned %d\n", status->ls_mdt_device,
1323                                        status->ls_registration, rec, rc);
1324                 }
1325                 if (!rc && !dryrun) {
1326                         status->ls_last_recno = rec;
1327                         lr_write_log();
1328
1329                 }
1330         }
1331
1332         return rc;
1333 }
1334
1335 /* Locate a usable version of rsync. At this point we'll use any
1336    version. */
1337 int lr_locate_rsync()
1338 {
1339         FILE *fp;
1340         int len;
1341
1342         /* Locate rsync */
1343         snprintf(rsync, PATH_MAX, "%s -p %s", TYPE, RSYNC);
1344         fp = popen(rsync, "r");
1345         if (fp == NULL)
1346                 return -1;
1347
1348         if (fgets(rsync, PATH_MAX, fp) == NULL) {
1349                 fclose(fp);
1350                 return -1;
1351         }
1352
1353         len = strlen(rsync);
1354         if (len > 0 && rsync[len - 1] == '\n')
1355                 rsync[len - 1] = '\0';
1356         fclose(fp);
1357
1358         /* Determine the version of rsync */
1359         snprintf(rsync_ver, PATH_MAX, "%s --version", rsync);
1360         fp = popen(rsync_ver, "r");
1361         if (fp == NULL)
1362                 return -1;
1363
1364         if (fgets(rsync_ver, PATH_MAX, fp) == NULL) {
1365                 fclose(fp);
1366                 return -1;
1367         }
1368         len = strlen(rsync_ver);
1369         if (len > 0 && rsync_ver[len - 1] == '\n')
1370                 rsync_ver[len - 1] = '\0';
1371         fclose(fp);
1372
1373         return 0;
1374
1375 }
1376
1377 /* Print the replication parameters */
1378 void lr_print_status(struct lr_info *info)
1379 {
1380         int i;
1381
1382         if (!verbose)
1383                 return;
1384
1385         printf("Lustre filesystem: %s\n", status->ls_source_fs);
1386         printf("MDT device: %s\n", status->ls_mdt_device);
1387         printf("Source: %s\n", status->ls_source);
1388         for (i = 0; i < status->ls_num_targets; i++)
1389                 printf("Target: %s\n", status->ls_targets[i]);
1390         if (statuslog != NULL)
1391                 printf("Statuslog: %s\n", statuslog);
1392         printf("Changelog registration: %s\n", status->ls_registration);
1393         printf("Starting changelog record: "LPD64"\n", status->ls_last_recno);
1394         if (noxattr)
1395                 printf("Replicate xattrs: no\n");
1396         if (noclear)
1397                 printf("Clear changelog after use: no\n");
1398         if (use_rsync)
1399                 printf("Using rsync: %s (%s)\n", rsync, rsync_ver);
1400 }
1401
1402 void lr_print_failure(struct lr_info *info, int rc)
1403 {
1404         fprintf(stderr, "Replication of operation failed(%d):"
1405                 " %lld %s (%d) %s %s %s\n", rc, info->recno,
1406                 changelog_type2str(info->type), info->type, info->tfid,
1407                 info->pfid, info->name);
1408 }
1409
1410 /* Replicate filesystem operations from src_path to target_path */
1411 int lr_replicate()
1412 {
1413         void *changelog_priv;
1414         struct lr_info *info;
1415         struct lr_info *ext = NULL;
1416         time_t start;
1417         int xattr_not_supp;
1418         int i;
1419         int rc;
1420
1421         start = time(NULL);
1422
1423         info = calloc(1, sizeof(struct lr_info));
1424         if (info == NULL)
1425                 return -ENOMEM;
1426
1427         rc = llapi_search_fsname(status->ls_source, status->ls_source_fs);
1428         if (rc) {
1429                 fprintf(stderr, "Source path is not a valid Lustre client "
1430                         "mountpoint.\n");
1431                 goto out;
1432         }
1433         if (status->ls_mdt_device[0] == '\0')
1434                 snprintf(status->ls_mdt_device, LR_NAME_MAXLEN, "%s%s",
1435                         status->ls_source_fs, DEFAULT_MDT);
1436
1437         ext = calloc(1, sizeof(struct lr_info));
1438         if (ext == NULL) {
1439                 rc = -ENOMEM;
1440                 goto out;
1441         }
1442
1443         for (i = 0, xattr_not_supp = 0; i < status->ls_num_targets; i++) {
1444                 snprintf(info->dest, PATH_MAX, "%s/%s", status->ls_targets[i],
1445                         SPECIAL_DIR);
1446                 rc = mkdir(info->dest, 0777);
1447                 if (rc == -1 && errno != EEXIST) {
1448                         fprintf(stderr, "Error writing to target path %s.\n",
1449                                 status->ls_targets[i]);
1450                         rc = -errno;
1451                         goto out;
1452                 }
1453                 rc = llistxattr(info->src, info->xlist, info->xsize);
1454                 if (rc == -1 && errno == ENOTSUP) {
1455                         fprintf(stderr, "xattrs not supported on %s\n",
1456                                 status->ls_targets[i]);
1457                         xattr_not_supp++;
1458                 }
1459         }
1460         if (xattr_not_supp == status->ls_num_targets)
1461                 /* None of the targets support xattrs. */
1462                 noxattr = 1;
1463
1464         lr_print_status(info);
1465
1466         /* Open changelogs for consumption*/
1467         rc = llapi_changelog_start(&changelog_priv, CHANGELOG_FLAG_BLOCK,
1468                                    status->ls_source_fs, status->ls_last_recno);
1469         if (rc < 0) {
1470                 fprintf(stderr, "Error opening changelog file for fs %s.\n",
1471                         status->ls_source_fs);
1472                 goto out;
1473         }
1474
1475         while (!quit && lr_parse_line(changelog_priv, info) == 0) {
1476                 rc = 0;
1477                 if (info->type == CL_RENAME && !info->is_extended) {
1478                         /* Newer rename operations extends changelog to store
1479                          * source file information, but old changelog has
1480                          * another record.
1481                          */
1482                         if (lr_parse_line(changelog_priv, ext) != 0)
1483                                 break;
1484                         memcpy(info->sfid, info->tfid, sizeof(info->sfid));
1485                         memcpy(info->spfid, info->pfid, sizeof(info->spfid));
1486                         memcpy(info->tfid, ext->tfid, sizeof(info->tfid));
1487                         memcpy(info->pfid, ext->pfid, sizeof(info->pfid));
1488                         strncpy(info->sname, info->name, sizeof(info->sname));
1489                         strncpy(info->name, ext->name, sizeof(info->name));
1490                         info->is_extended = 1;
1491                 }
1492
1493                 if (dryrun)
1494                         continue;
1495
1496                 DEBUG_ENTRY(info);
1497
1498                 switch(info->type) {
1499                 case CL_CREATE:
1500                 case CL_MKDIR:
1501                 case CL_MKNOD:
1502                 case CL_SOFTLINK:
1503                         rc = lr_create(info);
1504                         break;
1505                 case CL_RMDIR:
1506                 case CL_UNLINK:
1507                         rc = lr_remove(info);
1508                         break;
1509                 case CL_RENAME:
1510                         rc = lr_move(info);
1511                         break;
1512                 case CL_HARDLINK:
1513                         rc = lr_link(info);
1514                         break;
1515                 case CL_TRUNC:
1516                 case CL_SETATTR:
1517                         rc = lr_setattr(info);
1518                         break;
1519                 case CL_XATTR:
1520                         rc = lr_setxattr(info);
1521                         break;
1522                 case CL_CLOSE:
1523                 case CL_EXT:
1524                 case CL_OPEN:
1525                 case CL_LAYOUT:
1526                 case CL_MARK:
1527                         /* Nothing needs to be done for these entries */
1528                         /* fallthrough */
1529                 default:
1530                         break;
1531                 }
1532                 DEBUG_EXIT(info, rc);
1533                 if (rc && rc != -ENOENT) {
1534                         lr_print_failure(info, rc);
1535                         errors++;
1536                         if (abort_on_err)
1537                                 break;
1538                 }
1539                 lr_clear_cl(info, 0);
1540                 if (debug) {
1541                         bzero(info, sizeof(struct lr_info));
1542                         bzero(ext, sizeof(struct lr_info));
1543                 }
1544         }
1545
1546         llapi_changelog_fini(&changelog_priv);
1547
1548         if (errors || verbose)
1549                 printf("Errors: %d\n", errors);
1550
1551         /* Clear changelog records used so far */
1552         lr_clear_cl(info, 1);
1553
1554         if (verbose) {
1555                 printf("lustre_rsync took %ld seconds\n", time(NULL) - start);
1556                 printf("Changelog records consumed: %lld\n", rec_count);
1557         }
1558
1559         rc = 0;
1560
1561 out:
1562         if (info != NULL)
1563                 free(info);
1564         if (ext != NULL)
1565                 free(ext);
1566
1567         return rc;
1568 }
1569
1570 void
1571 termination_handler (int signum)
1572 {
1573         /* Set a flag for the replicator to gracefully shutdown */
1574         quit = 1;
1575         printf("lustre_rsync halting.\n");
1576 }
1577
1578 int main(int argc, char *argv[])
1579 {
1580         int newsize;
1581         int numtargets = 0;
1582         int rc = 0;
1583
1584         if ((rc = lr_init_status()) != 0)
1585                 return rc;
1586
1587         while ((rc = getopt_long(argc, argv, "as:t:m:u:l:vx:zc:ry:n:d:D:",
1588                                  long_opts, NULL)) >= 0) {
1589                 switch (rc) {
1590                 case 'a':
1591                         /* Assume absolute paths */
1592                         abort_on_err++;
1593                         break;
1594                 case 's':
1595                         /* Assume absolute paths */
1596                         strncpy(status->ls_source, optarg, PATH_MAX);
1597                         break;
1598                 case 't':
1599                         status->ls_num_targets++;
1600                         numtargets++;
1601                         if (numtargets != status->ls_num_targets) {
1602                                 /* Targets were read from a log
1603                                    file. The ones specified on the
1604                                    command line take precedence. The
1605                                    ones from the log file will be
1606                                    ignored. */
1607                                 status->ls_num_targets = numtargets;
1608                         }
1609                         newsize = sizeof (struct lustre_rsync_status) +
1610                                 (status->ls_num_targets * (PATH_MAX + 1));
1611                         if (status->ls_size != newsize) {
1612                                 status->ls_size = newsize;
1613                                 status = lr_grow_buf(status, newsize);
1614                                 if (status == NULL)
1615                                         return -ENOMEM;
1616                         }
1617                         strncpy(status->ls_targets[status->ls_num_targets - 1],
1618                                 optarg,
1619                                 PATH_MAX);
1620                         break;
1621                 case 'm':
1622                         strncpy(status->ls_mdt_device, optarg, LR_NAME_MAXLEN);
1623                         break;
1624                 case 'u':
1625                         strncpy(status->ls_registration, optarg,
1626                                 LR_NAME_MAXLEN);
1627                         break;
1628                 case 'l':
1629                         statuslog = optarg;
1630                         (void) lr_read_log();
1631                         break;
1632                 case 'v':
1633                         verbose++;
1634                         break;
1635                 case 'x':
1636                         if (strcmp("no", optarg) == 0) {
1637                                 noxattr = 1;
1638                         } else if (strcmp("yes", optarg) != 0) {
1639                                 printf("Invalid parameter %s. "
1640                                        "Specify --xattr=no or --xattr=yes\n",
1641                                        optarg);
1642                                 return -1;
1643                         }
1644                         break;
1645                 case 'z':
1646                         dryrun = 1;
1647                         break;
1648                 case 'c':
1649                         /* Undocumented option cl-clear */
1650                         if (strcmp("no", optarg) == 0) {
1651                                 noclear = 1;
1652                         } else if (strcmp("yes", optarg) != 0) {
1653                                 printf("Invalid parameter %s. "
1654                                        "Specify --cl-clear=no "
1655                                        "or --cl-clear=yes\n",
1656                                        optarg);
1657                                 return -1;
1658                         }
1659                         break;
1660                 case 'r':
1661                         /* Undocumented option use-rsync */
1662                         use_rsync = 1;
1663                         break;
1664                 case 'y':
1665                         /* Undocumented option rsync-threshold */
1666                         rsync_threshold = atol(optarg);
1667                         break;
1668                 case 'n':
1669                         /* Undocumented option start-recno */
1670                         status->ls_last_recno = atol(optarg);
1671                         break;
1672                 case 'd':
1673                         /* Undocumented option debug */
1674                         debug = atoi(optarg);
1675                         if (debug < 0 || debug > 2)
1676                                 debug = 0;
1677                         break;
1678                 case 'D':
1679                         /* Undocumented option debug log file */
1680                         debug_log = fopen(optarg, "a");
1681                         if (debug_log == NULL) {
1682                                 printf("Cannot open %s for debug log\n",
1683                                        optarg);
1684                                 return -1;
1685                         }
1686                         break;
1687                 default:
1688                         fprintf(stderr, "error: %s: option '%s' "
1689                                 "unrecognized.\n", argv[0], argv[optind - 1]);
1690                         lr_usage();
1691                         return -1;
1692                 }
1693         }
1694
1695         if (status->ls_last_recno == -1)
1696                 status->ls_last_recno = 0;
1697         if (strnlen(status->ls_registration, LR_NAME_MAXLEN) == 0) {
1698                 /* No registration ID was passed in. */
1699                 printf("Please specify changelog consumer registration id.\n");
1700                 lr_usage();
1701                 return -1;
1702         }
1703         if (strnlen(status->ls_source, PATH_MAX) == 0) {
1704                 fprintf(stderr, "Please specify the source path.\n");
1705                 lr_usage();
1706                 return -1;
1707         }
1708         if (strnlen(status->ls_targets[0], PATH_MAX) == 0) {
1709                 fprintf(stderr, "Please specify the target path.\n");
1710                 lr_usage();
1711                 return -1;
1712         }
1713
1714         /* This plumbing is needed for some of the ioctls behind
1715            llapi calls to work. */
1716         if (obd_initialize(argc, argv) < 0) {
1717                 fprintf(stderr, "obd_initialize failed.\n");
1718                 exit(-1);
1719         }
1720
1721         rc = lr_locate_rsync();
1722         if (use_rsync && rc != 0) {
1723                 fprintf(stderr, "Error: unable to locate %s.\n", RSYNC);
1724                 exit(-1);
1725         }
1726
1727         signal(SIGINT, termination_handler);
1728         signal(SIGHUP, termination_handler);
1729         signal(SIGTERM, termination_handler);
1730
1731         rc = lr_replicate();
1732
1733         if (debug_log != NULL)
1734                 fclose(debug_log);
1735         return rc;
1736 }