Whamcloud - gitweb
b1b64e46648d544c3f88794e22dbf13676039b64
[fs/lustre-release.git] / lustre / utils / lreplicate.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/lreplicate.c
37  *
38  * Author: Kalpak Shah <Kalpak.Shah@Sun.COM>
39  * Author: Manoj Joseph <Manoj.Joseph@Sun.COM>
40  */
41
42 /*
43  * - lreplicate 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  * - lreplicate 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, lreplicate 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 "lreplicate.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 lreplicate_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, "\tlreplicate -s <lustre_root_path> -t <target_path> "
221                 "-m <mdt> -r <user id> -l <status log>\n"
222                 "lreplicate can also pick up parameters from a "
223                 "status log created earlier.\n"
224                 "\tlreplicate -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 + 2);
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 + 2);
614         strcpy(p->pc_log.pcl_tfid, tfid + 2);
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 + 2) == 0 &&
668                     strcmp(curr->pc_log.pcl_tfid, tfid + 2) == 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 + 2);
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 /* Remove a file under SPECIAL_DIR with its tfid as its name. */
712 int lr_rm_special(struct lr_info *info)
713 {
714         int rc;
715
716         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
717                  status->ls_targets[info->target_no], SPECIAL_DIR,
718                  info->tfid + 2);
719         rc = lr_rmfile(info);
720
721         if (rc)
722                 lr_debug(DINFO, "remove: %s; rc=%d, errno=%d\n",
723                          info->dest, rc, errno);
724         return rc;
725 }
726
727 /* Replicate file and directory create events */
728 int lr_create(struct lr_info *info)
729 {
730         int len;
731         int rc1 = 0;
732         int rc;
733         int mkspecial = 0;
734
735         /* Is target FID present on the source? */
736         rc = lr_get_path(info, info->tfid + 3);
737         if (rc == -ENOENT) {
738                 /* Source file has disappeared. Not an error. */
739                 lr_debug(DINFO, "create: tfid %s not found on"
740                          "source-fs\n", info->tfid);
741                 return 0;
742         } else if (rc) {
743                 return rc;
744         }
745         strcpy(info->savedpath, info->path);
746
747         /* Is parent FID present on the source */
748         rc = lr_get_path(info, info->pfid + 3);
749         if (rc == -ENOENT) {
750                 lr_debug(DINFO, "create: pfid %s not found on source-fs\n",
751                          info->tfid);
752                 mkspecial = 1;
753         } else if (rc < 0) {
754                 return rc;
755         }
756
757         /* Is f2p(pfid)+name != f2p(tfid)? If not the file has moved. */
758         len = strlen(info->path);
759         if (len - 1 >= 0 && info->path[len - 1] == '/')
760                 snprintf(info->dest, PATH_MAX, "%s%s", info->path, info->name);
761         else
762                 snprintf(info->dest, PATH_MAX, "%s/%s", info->path, info->name);
763
764         lr_debug(DTRACE, "dest = %s; savedpath = %s\n", info->dest,
765                  info->savedpath);
766         if (strncmp(info->dest, info->savedpath, PATH_MAX) != 0) {
767                 lr_debug(DTRACE, "create: file moved (%s). %s != %s\n",
768                          info->tfid, info->dest, info->savedpath);
769                 mkspecial = 1;
770         }
771
772         /* Is f2p(pfid) present on the target? If not, the parent has
773            moved */
774         if (!mkspecial) {
775                 snprintf(info->dest, PATH_MAX, "%s%s", status->ls_targets[0],
776                         info->path);
777                 if (access(info->dest, F_OK) != 0)
778                         mkspecial = 1;
779         }
780         for (info->target_no = 0; info->target_no < status->ls_num_targets;
781              info->target_no++) {
782                 snprintf(info->dest, PATH_MAX, "%s%s",
783                         status->ls_targets[info->target_no], info->savedpath);
784                 lr_get_FID_PATH(status->ls_source, info->tfid, info->src,
785                                     PATH_MAX);
786
787                 if (!mkspecial)
788                         rc1 = lr_mkfile(info);
789                 if (mkspecial || rc1 == -ENOENT) {
790                         rc1 = lr_mk_special(info);
791                 }
792                 if (rc1)
793                         rc = rc1;
794         }
795         return rc;
796 }
797
798 /* Replicate a file remove (rmdir/unlink) operation */
799 int lr_remove(struct lr_info *info)
800 {
801         int rc = 0;
802         int rc1;
803
804         for (info->target_no = 0; info->target_no < status->ls_num_targets;
805              info->target_no++) {
806
807                 rc1 = lr_rm_special(info);
808                 if (!rc1)
809                         continue;
810
811                 rc1 = lr_get_path(info, info->pfid + 3);
812                 if (rc1 == -ENOENT) {
813                         lr_debug(DINFO, "remove: pfid %s not found\n",
814                                  info->pfid);
815                         continue;
816                 }
817                 if (rc1) {
818                         rc = rc1;
819                         continue;
820                 }
821                 snprintf(info->dest, PATH_MAX, "%s%s/%s",
822                         status->ls_targets[info->target_no], info->path,
823                         info->name);
824
825                 rc1 = lr_rmfile(info);
826                 lr_debug(DINFO, "remove: %s; rc1=%d, errno=%d\n",
827                          info->dest, rc1, errno);
828                 if (rc1) {
829                         rc = rc1;
830                         continue;
831                 }
832         }
833         return rc;
834 }
835
836 /* Replicate a rename/move operation. This operations are tracked by
837    two changelog records. */
838 int lr_move(struct lr_info *info, struct lr_info *ext)
839 {
840         int rc = 0;
841         int rc1;
842         int rc_dest, rc_src;
843         int special_src = 0;
844         int special_dest = 0;
845
846         rc_dest = lr_get_path(ext, ext->pfid + 3);
847         if (rc_dest < 0 && rc_dest != -ENOENT)
848                 return rc_dest;
849
850         rc_src = lr_get_path(info, info->pfid + 3);
851         if (rc_src < 0 && rc_src != -ENOENT)
852                 return rc_src;
853
854         for (info->target_no = 0; info->target_no < status->ls_num_targets;
855              info->target_no++) {
856
857                 if (!rc_dest) {
858                         snprintf(info->dest, PATH_MAX, "%s%s",
859                                 status->ls_targets[info->target_no],
860                                 ext->path);
861                         if (access(info->dest, F_OK) != 0) {
862                                 rc_dest = -errno;
863                         } else {
864                                 snprintf(info->dest, PATH_MAX, "%s%s/%s",
865                                         status->ls_targets[info->target_no],
866                                         ext->path, ext->name);
867                         }
868                 }
869                 if (rc_dest == -ENOENT) {
870                         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
871                                 status->ls_targets[info->target_no],
872                                 SPECIAL_DIR, info->tfid + 2);
873                         special_dest = 1;
874                 }
875
876                 if (!rc_src)
877                         snprintf(info->src, PATH_MAX, "%s%s/%s",
878                                 status->ls_targets[info->target_no],
879                                 info->path, info->name);
880                 if (rc_src == -ENOENT || (access(info->src, F_OK) != 0 &&
881                                           errno == ENOENT)) {
882                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
883                                 status->ls_targets[info->target_no],
884                                 SPECIAL_DIR, info->tfid + 2);
885                         special_src = 1;
886                 }
887
888                 rc1 = 0;
889                 if (strcmp(info->src, info->dest) != 0) {
890                         rc1 = rename(info->src, info->dest);
891                         if (rc1 == -1)
892                                 rc1 = -errno;
893                 }
894
895                 if (special_src) {
896                         lr_remove_pc(info->pfid, info->tfid);
897                         if (!special_dest)
898                                 lr_cascade_move(info->tfid + 2, info->dest, info);
899                 }
900                 if (special_dest)
901                         lr_add_pc(ext->pfid, info->tfid, ext->name);
902
903                 lr_debug(DINFO, "move: %s [to] %s rc1=%d, errno=%d\n",
904                          info->src, info->dest, rc1, errno);
905                 if (rc1)
906                         rc = rc1;
907         }
908         return rc;
909 }
910
911 /* Replicate a hard link */
912 int lr_link(struct lr_info *info)
913 {
914         int i;
915         int len;
916         int rc;
917         int rc1;
918         struct stat st;
919
920         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
921         rc = stat(info->src, &st);
922         if (rc == -1)
923                 return -errno;
924
925         for (info->target_no = 0; info->target_no < status->ls_num_targets;
926              info->target_no++) {
927
928                 info->src[0] = 0;
929                 info->dest[0] = 0;
930                 rc1 = 0;
931
932                 /* Search through the hardlinks to get the src and dest */
933                 for (i = 0; i < st.st_nlink && (info->src[0] == 0 ||
934                                                 info->dest[0] == 0); i++) {
935                         rc1 = lr_get_path_ln(info, info->tfid + 3, i);
936                         lr_debug(rc1 ? 0:DTRACE, "\tfid2path %s, %s, %d rc=%d\n",
937                                  info->path, info->name, i, rc1);
938                         if (rc1)
939                                 break;
940
941                         len = strlen(info->path) - strlen(info->name);
942                         if (len > 0 && strcmp(info->path + len,
943                                               info->name) == 0)
944                                 snprintf(info->dest, PATH_MAX, "%s%s",
945                                         status->ls_targets[info->target_no],
946                                         info->path);
947                         else if (info->src[0] == 0)
948                                 snprintf(info->src, PATH_MAX, "%s%s",
949                                         status->ls_targets[info->target_no],
950                                         info->path);
951                 }
952
953                 if (rc1) {
954                         rc = rc1;
955                         continue;
956                 }
957
958                 if (info->src[0] == 0 || info->dest[0] == 0)
959                         /* Could not find the source or destination.
960                          This can happen when some links don't exist
961                          anymore. */
962                         return -EINVAL;
963
964                 if (info->src[0] == 0)
965                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
966                                 status->ls_targets[info->target_no],
967                                 SPECIAL_DIR, info->tfid + 2);
968                 else if (info->dest[0] == 0)
969                         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
970                                 status->ls_targets[info->target_no],
971                                 SPECIAL_DIR, info->tfid + 2);
972
973                 rc1 = link(info->src, info->dest);
974                 lr_debug(rc1?0:DINFO, "link: %s [to] %s; rc1=%d %s\n",
975                          info->src, info->dest, rc1, strerror(errno));
976
977                 if (rc1)
978                         rc = rc1;
979         }
980         return rc;
981 }
982
983 /* Replicate file attributes */
984 int lr_setattr(struct lr_info *info)
985 {
986         int rc1;
987         int rc;
988
989         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
990
991         rc = lr_get_path(info, info->tfid + 3);
992         if (rc == -ENOENT)
993                 lr_debug(DINFO, "setattr: %s not present on source-fs\n",
994                          info->src);
995         if (rc)
996                 return rc;
997
998         for (info->target_no = 0; info->target_no < status->ls_num_targets;
999              info->target_no++) {
1000
1001                 snprintf(info->dest, PATH_MAX, "%s%s",
1002                          status->ls_targets[info->target_no], info->path);
1003                 lr_debug(DINFO, "setattr: %s %s %s", info->src, info->dest,
1004                          info->tfid);
1005
1006                 rc1 = lr_sync_data(info);
1007                 if (!rc1)
1008                         rc1 = lr_copy_attr(info->src, info->dest);
1009                 if (rc1)
1010                         rc = rc1;
1011         }
1012         return rc;
1013 }
1014
1015 /* Replicate xattrs */
1016 int lr_setxattr(struct lr_info *info)
1017 {
1018         int rc, rc1;
1019
1020         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
1021
1022         rc = lr_get_path(info, info->tfid + 3);
1023         if (rc == -ENOENT)
1024                 lr_debug(DINFO, "setxattr: %s not present on source-fs\n",
1025                          info->src);
1026         if (rc)
1027                 return rc;
1028
1029         for (info->target_no = 0; info->target_no < status->ls_num_targets;
1030              info->target_no++) {
1031
1032                 snprintf(info->dest, PATH_MAX, "%s%s",
1033                         status->ls_targets[info->target_no], info->path);
1034                 lr_debug(DINFO, "setxattr: %s %s %s\n", info->src, info->dest,
1035                          info->tfid);
1036
1037                 rc1 = lr_copy_xattr(info);
1038                 if (rc1)
1039                         rc = rc1;
1040         }
1041
1042         return rc;
1043 }
1044
1045 /* Parse a line of changelog entry */
1046 int lr_parse_line(struct lr_info *info, FILE *fp)
1047 {
1048         unsigned long long time;
1049         unsigned int flags;
1050         char typestr[TYPE_STR_LEN];
1051         char line[PATH_MAX];
1052         char *str;
1053         int i;
1054
1055         if (fgets(line, sizeof(line), fp) != NULL) {
1056                 if (sscanf(line, "%llu %s %llu %x %s %s",
1057                            &info->recno, typestr, &time,
1058                            &flags, info->tfid, info->pfid) < 4) {
1059                         fprintf(stderr, "error: unexpected changelog record "
1060                                 "format - %s\n", line);
1061                         return -1;
1062                 }
1063                 typestr[2] = '\0';
1064                 info->type = atoi(typestr);
1065
1066                 /* The filename could have spaces in it. scanf would
1067                    have ignored it. Parse for the complete
1068                    filename. */
1069                 if (info->type != CL_SETATTR &&
1070                     info->type != CL_XATTR &&
1071                     info->type != CL_MARK) {
1072                         for (i = 0, str = line; str != NULL && i <= 5;
1073                              i++, str++){
1074                                 str = strchr(str, ' ');
1075                         }
1076                         if (str) {
1077                                 strncpy(info->name, str, PATH_MAX);
1078                                 str = strchr(info->name, '\n');
1079                                 if (str)
1080                                         str[0] = '\0';
1081                         } else {
1082                                 fprintf(stderr, "error: unexpected changelog "
1083                                         "record format - %s\n", line);
1084                                 return -1;
1085                         }
1086                 }
1087                 rec_count++;
1088         } else {
1089                 return -1;
1090         }
1091         return 0;
1092 }
1093
1094 /* Initialize the replication parameters */
1095 int lr_init_status()
1096 {
1097         size_t size = sizeof(struct lreplicate_status) + PATH_MAX;
1098
1099         if (status != NULL)
1100                 return 0;
1101         status = calloc(size, 1);
1102         if (status == NULL)
1103                 return -ENOMEM;
1104         status->ls_version = REPLICATE_STATUS_VER;
1105         status->ls_size = size;
1106         status->ls_last_recno = -1;
1107         return 0;
1108 }
1109
1110 /* Make a backup of the statuslog */
1111 void lr_backup_log()
1112 {
1113         char backupfile[PATH_MAX];
1114
1115         if (logbackedup)
1116                 return;
1117         snprintf(backupfile, PATH_MAX, "%s.old", statuslog);
1118         (void) rename(statuslog, backupfile);
1119         logbackedup = 1;
1120
1121         return;
1122 }
1123
1124 /* Save replication parameters to a statuslog. */
1125 int lr_write_log()
1126 {
1127         int fd;
1128         size_t size;
1129         size_t write_size = status->ls_size;
1130         struct lr_parent_child_list *curr;
1131         int rc = 0;
1132
1133         if (statuslog == NULL)
1134                 return 0;
1135
1136         lr_backup_log();
1137
1138         fd = open(statuslog, O_WRONLY | O_CREAT | O_SYNC);
1139         if (fd == -1) {
1140                 fprintf(stderr, "Error opening log file for writing (%s)\n",
1141                         statuslog);
1142                 return -1;
1143         }
1144         errno = 0;
1145         size = write(fd, status, write_size);
1146         if (size != write_size) {
1147                 fprintf(stderr, "Error writing to log file (%s) %d\n",
1148                         statuslog, errno);
1149                 close(fd);
1150                 return -1;
1151         }
1152
1153         for (curr = parents; curr; curr = curr->pc_next) {
1154                 size = write(fd, &curr->pc_log, sizeof(curr->pc_log));
1155                 if (size != sizeof(curr->pc_log)) {
1156                         fprintf(stderr, "Error writing to log file (%s) %d\n",
1157                                 statuslog, errno);
1158                         rc = -1;
1159                         break;
1160                 }
1161         }
1162         close(fd);
1163         return rc;
1164 }
1165
1166 /* Read statuslog and populate the replication parameters.  Command
1167  * line parameters take precedence over parameters in the log file.*/
1168 int lr_read_log()
1169 {
1170         struct lr_parent_child_list *tmp;
1171         struct lr_parent_child_log rec;
1172         struct lreplicate_status *s;
1173         int fd = -1;
1174         size_t size;
1175         size_t read_size = sizeof(struct lreplicate_status) + PATH_MAX;
1176         int rc = 0;
1177
1178         if (statuslog == NULL)
1179                 return 0;
1180
1181         s = calloc(1, read_size);
1182         if (s == NULL)
1183                 GOTO(out, rc = -ENOMEM);
1184
1185         fd = open(statuslog, O_RDONLY);
1186         if (fd == -1)
1187                 GOTO(out, rc = -errno);
1188         size = read(fd, s, read_size);
1189         if (size != read_size)
1190                 GOTO(out, rc = -EINVAL);
1191         if (read_size < s->ls_size) {
1192                 read_size = s->ls_size;
1193                 s = lr_grow_buf(s, read_size);
1194                 if (s == NULL)
1195                         GOTO(out, rc = -ENOMEM);
1196                 if (lseek(fd, 0, SEEK_SET) == -1)
1197                         GOTO(out, rc = -errno);
1198                 size = read(fd, s, read_size);
1199                 if (size != read_size)
1200                         GOTO(out, rc = -EINVAL);
1201         }
1202
1203         while (read(fd, &rec, sizeof(rec)) != 0) {
1204                 tmp = calloc(1, sizeof(*tmp));
1205                 if (!tmp)
1206                         GOTO(out, rc = -ENOMEM);
1207                 tmp->pc_log = rec;
1208                 tmp->pc_next = parents;
1209                 parents = tmp;
1210         }
1211
1212         /* copy uninitialized fields to status */
1213         if (status->ls_num_targets == 0) {
1214                 if (status->ls_size != s->ls_size) {
1215                         status = lr_grow_buf(status, s->ls_size);
1216                         if (status == NULL)
1217                                 GOTO(out, rc = -ENOMEM);
1218                         status->ls_size = s->ls_size;
1219                 }
1220                 status->ls_num_targets = s->ls_num_targets;
1221                 memcpy(status->ls_targets, s->ls_targets,
1222                        PATH_MAX * s->ls_num_targets);
1223         }
1224         if (status->ls_last_recno == -1)
1225                 status->ls_last_recno = s->ls_last_recno;
1226
1227         if (status->ls_registration[0] == '\0')
1228                 strncpy(status->ls_registration, s->ls_registration,
1229                         LR_NAME_MAXLEN);
1230
1231         if (status->ls_mdt_device[0] == '\0')
1232                 strncpy(status->ls_mdt_device, s->ls_mdt_device,
1233                         LR_NAME_MAXLEN);
1234
1235         if (status->ls_source_fs[0] == '\0')
1236                 strncpy(status->ls_source_fs, s->ls_source_fs,
1237                         LR_NAME_MAXLEN);
1238
1239         if (status->ls_source[0] == '\0')
1240                 strncpy(status->ls_source, s->ls_source, PATH_MAX);
1241
1242  out:
1243         if (fd != -1)
1244                 close(fd);
1245         if (s)
1246                 free(s);
1247         return rc;
1248 }
1249
1250 /* Clear changelogs every CLEAR_INTERVAL records or at the end of
1251    processing. */
1252 int lr_clear_cl(struct lr_info *info, int force)
1253 {
1254         char    mdt_device[LR_NAME_MAXLEN + 1];
1255         long long rec;
1256         int rc = 0;
1257
1258         if (force || info->recno > status->ls_last_recno + CLEAR_INTERVAL) {
1259                 if (info->type == CL_RENAME)
1260                         rec = info->recno + 1;
1261                 else
1262                         rec = info->recno;
1263                 if (!noclear && !dryrun) {
1264                         /* llapi_changelog_clear modifies the mdt
1265                          * device name so make a copy of it until this
1266                          * is fixed.
1267                         */
1268                         strncpy(mdt_device, status->ls_mdt_device,
1269                                 LR_NAME_MAXLEN);
1270                         rc = llapi_changelog_clear(mdt_device,
1271                                                    status->ls_registration,
1272                                                    rec);
1273                         if (rc)
1274                                 printf("Changelog clear (%s, %s, %lld) "
1275                                        "returned %d\n", status->ls_mdt_device,
1276                                        status->ls_registration, rec, rc);
1277                 }
1278                 if (!rc && !dryrun) {
1279                         status->ls_last_recno = rec;
1280                         lr_write_log();
1281
1282                 }
1283         }
1284
1285         return rc;
1286 }
1287
1288 /* Locate a usable version of rsync. At this point we'll use any
1289    version. */
1290 int lr_locate_rsync()
1291 {
1292         FILE *fp;
1293         int len;
1294
1295         /* Locate rsync */
1296         snprintf(rsync, PATH_MAX, "%s -p %s", TYPE, RSYNC);
1297         fp = popen(rsync, "r");
1298         if (fp == NULL)
1299                 return -1;
1300
1301         if (fgets(rsync, PATH_MAX, fp) == NULL) {
1302                 fclose(fp);
1303                 return -1;
1304         }
1305
1306         len = strlen(rsync);
1307         if (len > 0 && rsync[len - 1] == '\n')
1308                 rsync[len - 1] = '\0';
1309         fclose(fp);
1310
1311         /* Determine the version of rsync */
1312         snprintf(rsync_ver, PATH_MAX, "%s --version", rsync);
1313         fp = popen(rsync_ver, "r");
1314         if (fp == NULL)
1315                 return -1;
1316
1317         if (fgets(rsync_ver, PATH_MAX, fp) == NULL) {
1318                 fclose(fp);
1319                 return -1;
1320         }
1321         len = strlen(rsync_ver);
1322         if (len > 0 && rsync_ver[len - 1] == '\n')
1323                 rsync_ver[len - 1] = '\0';
1324         fclose(fp);
1325
1326         return 0;
1327
1328 }
1329
1330 /* Print the replication parameters */
1331 void lr_print_status(struct lr_info *info)
1332 {
1333         int i;
1334
1335         if (!verbose)
1336                 return;
1337
1338         printf("Lustre filesystem: %s\n", status->ls_source_fs);
1339         printf("MDT device: %s\n", status->ls_mdt_device);
1340         printf("Source: %s\n", status->ls_source);
1341         for (i = 0; i < status->ls_num_targets; i++)
1342                 printf("Target: %s\n", status->ls_targets[i]);
1343         if (statuslog != NULL)
1344                 printf("Statuslog: %s\n", statuslog);
1345         printf("Changelog registration: %s\n", status->ls_registration);
1346         printf("Starting changelog record: %lld\n", status->ls_last_recno);
1347         if (noxattr)
1348                 printf("Replicate xattrs: no\n");
1349         if (noclear)
1350                 printf("Clear changelog after use: no\n");
1351         if (use_rsync)
1352                 printf("Using rsync: %s (%s)\n", rsync, rsync_ver);
1353 }
1354
1355 DECLARE_CHANGELOG_NAMES;
1356
1357 void lr_print_failure(struct lr_info *info, int rc)
1358 {
1359         fprintf(stderr, "Replication of operation failed(%d):"
1360                 " %lld %s (%d) %s %s %s\n", rc, info->recno, 
1361                 changelog_str[info->type], info->type, info->tfid,
1362                 info->pfid, info->name);
1363 }
1364
1365 /* Replicate filesystem operations from src_path to target_path */
1366 int lr_replicate()
1367 {
1368         int fd;
1369         FILE *fp;
1370         long long startrec;
1371         struct lr_info *info;
1372         struct lr_info *ext;
1373         time_t start;
1374         int xattr_not_supp;
1375         int i;
1376         int rc;
1377
1378         start = time(NULL);
1379
1380         info = calloc(1, sizeof(struct lr_info));
1381         if (info == NULL)
1382                 return -ENOMEM;
1383
1384         rc = llapi_search_fsname(status->ls_source, status->ls_source_fs);
1385         if (rc) {
1386                 fprintf(stderr, "Source path is not a valid Lustre client "
1387                         "mountpoint.\n");
1388                 return rc;
1389         }
1390         if (status->ls_mdt_device[0] == '\0')
1391                 snprintf(status->ls_mdt_device, LR_NAME_MAXLEN, "%s%s",
1392                         status->ls_source_fs, DEFAULT_MDT);
1393
1394         ext = calloc(1, sizeof(struct lr_info));
1395         if (ext == NULL)
1396                 return -ENOMEM;
1397         memcpy(ext, info, sizeof(struct lr_info));
1398
1399         for (i = 0, xattr_not_supp = 0; i < status->ls_num_targets; i++) {
1400                 snprintf(info->dest, PATH_MAX, "%s/%s", status->ls_targets[i],
1401                         SPECIAL_DIR);
1402                 rc = mkdir(info->dest, 0777);
1403                 if (rc == -1 && errno != EEXIST) {
1404                         fprintf(stderr, "Error writing to target path %s.\n",
1405                                 status->ls_targets[i]);
1406                         return -errno;
1407                 }
1408                 rc = llistxattr(info->src, info->xlist, info->xsize);
1409                 if (rc == -1 && errno == ENOTSUP) {
1410                         fprintf(stderr, "xattrs not supported on %s\n",
1411                                 status->ls_targets[i]);
1412                         xattr_not_supp++;
1413                 }
1414         }
1415         if (xattr_not_supp == status->ls_num_targets)
1416                 /* None of the targets support xattrs. */
1417                 noxattr = 1;
1418
1419         lr_print_status(info);
1420
1421         /* Open changelogs for consumption*/
1422         startrec = status->ls_last_recno;
1423         fd = llapi_changelog_open(status->ls_source_fs, startrec);
1424         if (fd < 0) {
1425                 fprintf(stderr, "Error opening changelog file for fs %s.\n",
1426                         status->ls_source_fs);
1427                 return fd;
1428         }
1429         if ((fp = fdopen(fd, "r")) == NULL) {
1430                 fprintf(stderr, "Error: fdopen failed.");
1431                 close(fd);
1432                 return -errno;
1433         }
1434
1435         while (!quit && lr_parse_line(info, fp) == 0) {
1436                 rc = 0;
1437                 if (info->type == CL_RENAME)
1438                         /* Rename operations have an additional changelog
1439                            record of information. */
1440                         lr_parse_line(ext, fp);
1441
1442                 if (dryrun)
1443                         continue;
1444
1445                 switch(info->type) {
1446                 case CL_CREATE:
1447                 case CL_MKDIR:
1448                 case CL_MKNOD:
1449                 case CL_SOFTLINK:
1450                         rc = lr_create(info);
1451                         break;
1452                 case CL_RMDIR:
1453                 case CL_UNLINK:
1454                         rc = lr_remove(info);
1455                         break;
1456                 case CL_RENAME:
1457                         rc = lr_move(info, ext);
1458                         break;
1459                 case CL_HARDLINK:
1460                         rc = lr_link(info);
1461                         break;
1462                 case CL_TRUNC:
1463                 case CL_SETATTR:
1464                         rc = lr_setattr(info);
1465                         break;
1466                 case CL_XATTR:
1467                         rc = lr_setxattr(info);
1468                         break;
1469                 case CL_CLOSE:
1470                 case CL_EXT:
1471                 case CL_OPEN:
1472                 case CL_IOCTL:
1473                 case CL_MARK:
1474                         /* Nothing needs to be done for these entries */
1475                 default:
1476                         break;
1477                 }
1478                 if (rc && rc != -ENOENT) {
1479                         lr_print_failure(info, rc);
1480                         errors++;
1481                         if (abort_on_err)
1482                                 break;
1483                 }
1484                 lr_clear_cl(info, 0);
1485                 if (debug) {
1486                         bzero(info, sizeof(struct lr_info));
1487                         bzero(ext, sizeof(struct lr_info));
1488                 }
1489         }
1490
1491         if (errors || verbose)
1492                 printf("Errors: %d\n", errors);
1493
1494         /* Clear changelog records used so far */
1495         lr_clear_cl(info, 1);
1496
1497         if (verbose) {
1498                 printf("lreplicate took %ld seconds\n", time(NULL) - start);
1499                 printf("Changelog records consumed: %lld\n", rec_count);
1500         }
1501
1502         close(fd);
1503         fclose(fp);
1504
1505         return 0;
1506 }
1507
1508 void
1509 termination_handler (int signum)
1510 {
1511         /* Set a flag for the replicator to gracefully shutdown */
1512         quit = 1;
1513         printf("lreplicate halting.\n");
1514 }
1515
1516 int main(int argc, char *argv[])
1517 {
1518         char c;
1519         int newsize;
1520         int numtargets = 0;
1521         int rc = 0;
1522
1523         if ((rc = lr_init_status()) != 0)
1524                 return rc;
1525
1526         while ((c = getopt_long(argc, argv, "as:t:m:u:l:vx:zc:ry:n:d:",
1527                                 long_opts, NULL)) >= 0) {
1528                 switch (c) {
1529                 case 'a':
1530                         /* Assume absolute paths */
1531                         abort_on_err++;
1532                         break;
1533                 case 's':
1534                         /* Assume absolute paths */
1535                         strncpy(status->ls_source, optarg, PATH_MAX);
1536                         break;
1537                 case 't':
1538                         status->ls_num_targets++;
1539                         numtargets++;
1540                         if (numtargets != status->ls_num_targets) {
1541                                 /* Targets were read from a log
1542                                    file. The ones specified on the
1543                                    command line take precedence. The
1544                                    ones from the log file will be
1545                                    ignored. */
1546                                 status->ls_num_targets = numtargets;
1547                         }
1548                         newsize = sizeof (struct lreplicate_status) +
1549                                 (status->ls_num_targets * PATH_MAX);
1550                         if (status->ls_size != newsize) {
1551                                 status->ls_size = newsize;
1552                                 status = lr_grow_buf(status, newsize);
1553                                 if (status == NULL)
1554                                         return -ENOMEM;
1555                         }
1556                         strncpy(status->ls_targets[status->ls_num_targets - 1],
1557                                 optarg,
1558                                 PATH_MAX);
1559                         break;
1560                 case 'm':
1561                         strncpy(status->ls_mdt_device, optarg, LR_NAME_MAXLEN);
1562                         break;
1563                 case 'u':
1564                         strncpy(status->ls_registration, optarg,
1565                                 LR_NAME_MAXLEN);
1566                         break;
1567                 case 'l':
1568                         statuslog = optarg;
1569                         (void) lr_read_log();
1570                         break;
1571                 case 'v':
1572                         verbose++;
1573                         break;
1574                 case 'x':
1575                         if (strcmp("no", optarg) == 0) {
1576                                 noxattr = 1;
1577                         } else if (strcmp("yes", optarg) != 0) {
1578                                 printf("Invalid parameter %s. "
1579                                        "Specify --xattr=no or --xattr=yes\n",
1580                                        optarg);
1581                                 return -1;
1582                         }
1583                         break;
1584                 case 'z':
1585                         dryrun = 1;
1586                         break;
1587                 case 'c':
1588                         /* Undocumented option cl-clear */
1589                         if (strcmp("no", optarg) == 0) {
1590                                 noclear = 1;
1591                         } else if (strcmp("yes", optarg) != 0) {
1592                                 printf("Invalid parameter %s. "
1593                                        "Specify --cl-clear=no "
1594                                        "or --cl-clear=yes\n",
1595                                        optarg);
1596                                 return -1;
1597                         }
1598                         break;
1599                 case 'r':
1600                         /* Undocumented option use-rsync */
1601                         use_rsync = 1;
1602                         break;
1603                 case 'y':
1604                         /* Undocumented option rsync-threshold */
1605                         rsync_threshold = atol(optarg);
1606                         break;
1607                 case 'n':
1608                         /* Undocumented option start-recno */
1609                         status->ls_last_recno = atol(optarg);
1610                         break;
1611                 case 'd':
1612                         /* Undocumented option debug */
1613                         debug = atoi(optarg);
1614                         if (debug < 0 || debug > 2)
1615                                 debug = 0;
1616                         break;
1617                 default:
1618                         fprintf(stderr, "error: %s: option '%s' "
1619                                 "unrecognized.\n", argv[0], argv[optind - 1]);
1620                         lr_usage();
1621                         return -1;
1622                 }
1623         }
1624
1625         if (status->ls_last_recno == -1)
1626                 status->ls_last_recno = 0;
1627         if (strnlen(status->ls_registration, LR_NAME_MAXLEN) == 0) {
1628                 /* No registration ID was passed in. */
1629                 printf("Please specify changelog consumer registration id.\n");
1630                 lr_usage();
1631                 return -1;
1632         }
1633         if (strnlen(status->ls_source, PATH_MAX) == 0) {
1634                 fprintf(stderr, "Please specify the source path.\n");
1635                 lr_usage();
1636                 return -1;
1637         }
1638         if (strnlen(status->ls_targets[0], PATH_MAX) == 0) {
1639                 fprintf(stderr, "Please specify the target path.\n");
1640                 lr_usage();
1641                 return -1;
1642         }
1643
1644         /* This plumbing is needed for some of the ioctls behind
1645            llapi calls to work. */
1646         if (obd_initialize(argc, argv) < 0) {
1647                 fprintf(stderr, "obd_initialize failed.\n");
1648                 exit(-1);
1649         }
1650
1651         rc = lr_locate_rsync();
1652         if (use_rsync && rc != 0) {
1653                 fprintf(stderr, "Error: unable to locate %s.\n", RSYNC);
1654                 exit(-1);
1655         }
1656
1657         signal(SIGINT, termination_handler);
1658         signal(SIGHUP, termination_handler);
1659         signal(SIGTERM, termination_handler);
1660
1661         rc = lr_replicate();
1662
1663         return rc;
1664 }