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