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