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