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