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