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