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