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