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