Whamcloud - gitweb
LU-2062 utils: HSM Posix CopyTool
[fs/lustre-release.git] / lustre / utils / lhsmtool_posix.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.htm
19  *
20  * GPL HEADER END
21  */
22 /*
23  * (C) Copyright 2012 Commissariat a l'energie atomique et aux energies
24  *     alternatives
25  *
26  */
27 /* HSM copytool program for POSIX filesystem-based HSM's.
28  *
29  * An HSM copytool daemon acts on action requests from Lustre to copy files
30  * to and from an HSM archive system. This one in particular makes regular
31  * POSIX filesystem calls to a given path, where an HSM is presumably mounted.
32  *
33  * This particular tool can also import an existing HSM archive.
34  */
35
36 #include <utime.h>
37 #include <sys/xattr.h>
38 #include <dirent.h>
39 #include <stdlib.h>
40 #include <sys/errno.h>
41 #include <lustre/lustre_idl.h>
42 #include <lustre/lustreapi.h>
43
44 /* Progress reporting period */
45 #define REPORT_INTERVAL_DEFAULT 30
46 /* HSM hash subdir permissions */
47 #define DIR_PERM S_IRWXU
48 /* HSM hash file permissions */
49 #define FILE_PERM (S_IRUSR | S_IWUSR)
50
51 #define ONE_MB 0x100000
52
53 /* copytool uses a 32b bitmask field to register with kuc
54  * archive num = 0 => all
55  * archive num from 1 to 32
56  */
57 #define MAX_ARCHIVE_CNT (sizeof(__u32) * 8)
58
59 enum ct_action {
60         CA_IMPORT = 1,
61         CA_REBIND,
62         CA_MAXSEQ,
63         CA_DAEMON,
64 };
65
66 struct options {
67         int                      o_copy_attrs;
68         int                      o_dry_run;
69         int                      o_abort_on_error;
70         int                      o_shadow_tree;
71         int                      o_verbose;
72         int                      o_copy_xattrs;
73         int                      o_archive_cnt;
74         int                      o_archive_id[MAX_ARCHIVE_CNT];
75         int                      o_report_int;
76         unsigned long long       o_bandwidth;
77         size_t                   o_chunk_size;
78         enum ct_action           o_action;
79         char                    *o_mnt;
80         char                    *o_hsm_root;
81         char                    *o_src; /* for import, or rebind */
82         char                    *o_dst; /* for import, or rebind */
83 };
84
85 /* everything else is zeroed */
86 struct options opt = {
87         .o_copy_attrs = 1,
88         .o_shadow_tree = 1,
89         .o_verbose = LLAPI_MSG_WARN,
90         .o_copy_xattrs = 1,
91         .o_report_int = REPORT_INTERVAL_DEFAULT,
92         .o_chunk_size = ONE_MB,
93 };
94
95 /* The LLAPI will hold an open FD on lustre for us. Additionally open one on
96  * the archive FS root to make sure it doesn't drop out from under us (and
97  * remind the admin to shutdown the copytool before unmounting). */
98 static int arc_fd = -1;
99
100 static int err_major;
101 static int err_minor;
102
103 static char cmd_name[PATH_MAX];
104 static char fs_name[MAX_OBD_NAME + 1];
105
106 static struct hsm_copytool_private *ctdata;
107
108
109 #define CT_ERROR(format, ...) \
110         llapi_printf(LLAPI_MSG_ERROR, "%s: "format, cmd_name, ## __VA_ARGS__)
111 #define CT_DEBUG(format, ...) \
112         llapi_printf(LLAPI_MSG_DEBUG, "%s: "format, cmd_name, ## __VA_ARGS__)
113 #define CT_WARN(format, ...) \
114         llapi_printf(LLAPI_MSG_WARN, "%s: "format, cmd_name, ## __VA_ARGS__)
115 #define CT_TRACE(format, ...) \
116         llapi_printf(LLAPI_MSG_INFO, "%s: "format, cmd_name, ## __VA_ARGS__)
117
118 static void usage(const char *name, int rc)
119 {
120         fprintf(stdout,
121         " Usage: %s [options]... <mode> <lustre_mount_point>\n"
122         "The Lustre HSM Posix copy tool can be used as a daemon or "
123         "as a command line tool\n"
124         "The Lustre HSM daemon acts on action requests from Lustre\n"
125         "to copy files to and from an HSM archive system.\n"
126         "This POSIX-flavored daemon makes regular POSIX filesystem calls\n"
127         "to an HSM mounted at a given hsm_root.\n"
128         "   -d, --daemon        Daemon mode, run in background\n"
129         " Options:\n"
130         "   --no-attr           Don't copy file attributes\n"
131         "   --no-shadow         Don't create shadow namespace in archive\n"
132         "   --no-xattr          Don't copy file extended attributes\n"
133         "The Lustre HSM tool performs administrator-type actions\n"
134         "on a Lustre HSM archive.\n"
135         "This POSIX-flavored tool can link an existing HSM namespace\n"
136         "into a Lustre filesystem.\n"
137         " Usage:\n"
138         "   %s [options] --import <src> <dst> <lustre_mount_point>\n"
139         "      import an archived subtree at\n"
140         "       <src> (relative to hsm_root) into the Lustre filesystem at\n"
141         "       <dst> (absolute)\n"
142         "   %s [options] --rebind <old_FID> <new_FID> <lustre_mount_point>\n"
143         "      rebind an entry in the HSM to a new FID\n"
144         "       <old_FID> old FID the HSM entry is bound to\n"
145         "       <new_FID> new FID to bind the HSM entry to\n"
146         "   %s [options] --rebind <list_file> <lustre_mount_point>\n"
147         "      perform the rebind operation for all FID in the list file\n"
148         "       each line of <list_file> consists of <old_FID> <new_FID>\n"
149         "   %s [options] --max-sequence <fsname>\n"
150         "       return the max fid sequence of archived files\n"
151         "   -A, --archive <#>        Archive number (repeatable)\n"
152         "   -p, --hsm-root <path>    Target HSM mount point\n"
153         "   -q, --quiet              Produce less verbose output\n"
154         "   -v, --verbose            Produce more verbose output\n"
155         "   -c, --chunk-size <sz>    I/O size used during data copy\n"
156         "                            (unit can be used, default is MB)\n"
157         "   --abort-on-error         Abort operation on major error\n"
158         "   --dry-run                Don't run, just show what would be done\n"
159         "   --bandwidth <bw>         Limit I/O bandwidth (unit can be used\n,"
160         "                            default is MB)\n",
161         cmd_name, cmd_name, cmd_name, cmd_name, cmd_name);
162
163         exit(rc);
164 }
165
166 static int ct_parseopts(int argc, char * const *argv)
167 {
168         struct option long_opts[] = {
169                 {"abort-on-error", no_argument,       &opt.o_abort_on_error, 1},
170                 {"abort_on_error", no_argument,       &opt.o_abort_on_error, 1},
171                 {"archive",        required_argument, NULL,                'A'},
172                 {"bandwidth",      required_argument, NULL,                'b'},
173                 {"chunk-size",     required_argument, NULL,                'c'},
174                 {"chunk_size",     required_argument, NULL,                'c'},
175                 {"daemon",         no_argument,       NULL,                'd'},
176                 {"dry-run",        no_argument,       &opt.o_dry_run,       1},
177                 {"help",           no_argument,       NULL,                'h'},
178                 {"hsm-root",       required_argument, NULL,                'p'},
179                 {"hsm_root",       required_argument, NULL,                'p'},
180                 {"import",         no_argument,       NULL,                'i'},
181                 {"max-sequence",   no_argument,       NULL,                'M'},
182                 {"max_sequence",   no_argument,       NULL,                'M'},
183                 {"no-attr",        no_argument,       &opt.o_copy_attrs,    0},
184                 {"no_attr",        no_argument,       &opt.o_copy_attrs,    0},
185                 {"no-shadow",      no_argument,       &opt.o_shadow_tree,   0},
186                 {"no_shadow",      no_argument,       &opt.o_shadow_tree,   0},
187                 {"no-xattr",       no_argument,       &opt.o_copy_xattrs,   0},
188                 {"no_xattr",       no_argument,       &opt.o_copy_xattrs,   0},
189                 {"quiet",          no_argument,       NULL,                'q'},
190                 {"rebind",         no_argument,       NULL,                'r'},
191                 {"report",         required_argument, &opt.o_report_int,    0},
192                 {"verbose",        no_argument,       NULL,                'v'},
193                 {0, 0, 0, 0}
194         };
195         int                      c;
196         unsigned long long       value;
197         unsigned long long       unit;
198
199         optind = 0;
200         while ((c = getopt_long(argc, argv, "A:b:c:dhiMp:qruv",
201                                 long_opts, NULL)) != -1) {
202                 switch (c) {
203                 case 'A':
204                         if ((opt.o_archive_cnt >= MAX_ARCHIVE_CNT) ||
205                             (atoi(optarg) >= MAX_ARCHIVE_CNT)) {
206                                 CT_ERROR("archive number must be less"
207                                          "than %lu\n", MAX_ARCHIVE_CNT);
208                                 return -E2BIG;
209                         }
210                         opt.o_archive_id[opt.o_archive_cnt] = atoi(optarg);
211                         opt.o_archive_cnt++;
212                         break;
213                 case 'b': /* -b and -c have both a number with unit as arg */
214                 case 'c':
215                         unit = ONE_MB;
216                         if (llapi_parse_size(optarg, &value, &unit, 0) < 0) {
217                                 CT_ERROR("bad value for -%c '%s'\n", c, optarg);
218                                 return -EINVAL;
219                         }
220                         if (c == 'c')
221                                 opt.o_chunk_size = value;
222                         else
223                                 opt.o_bandwidth = value;
224                         break;
225                 case 'd':
226                         opt.o_action = CA_DAEMON;
227                         break;
228                 case 'h':
229                         usage(argv[0], 0);
230                 case 'i':
231                         opt.o_action = CA_IMPORT;
232                         break;
233                 case 'M':
234                         opt.o_action = CA_MAXSEQ;
235                         break;
236                 case 'p':
237                         opt.o_hsm_root = optarg;
238                         break;
239                 case 'q':
240                         opt.o_verbose--;
241                         break;
242                 case 'r':
243                         opt.o_action = CA_REBIND;
244                         break;
245                 case 'v':
246                         opt.o_verbose++;
247                         break;
248                 case 0:
249                         break;
250                 default:
251                         CT_ERROR("unrecognized option '%s'\n",
252                                  argv[optind - 1]);
253                         return -EINVAL;
254                 }
255         }
256
257         switch (opt.o_action) {
258         case CA_IMPORT:
259                 /* src dst mount_point */
260                 if (argc != optind + 3) {
261                         CT_ERROR("--import requires 2 arguments\n");
262                         return -EINVAL;
263                 }
264                 opt.o_src = argv[optind++];
265                 opt.o_dst = argv[optind++];
266                 break;
267         case CA_REBIND:
268                 /* FID1 FID2 mount_point or FILE mount_point */
269                 if (argc == optind + 2) {
270                         opt.o_src = argv[optind++];
271                         opt.o_dst = NULL;
272                 } else if (argc == optind + 3) {
273                         opt.o_src = argv[optind++];
274                         opt.o_dst = argv[optind++];
275                 } else {
276                         CT_ERROR("--rebind requires 1 or 2 arguments\n");
277                         return -EINVAL;
278                 }
279                 break;
280         case CA_MAXSEQ:
281         default:
282                 /* just mount point */
283                 break;
284         }
285
286         if (argc != optind + 1) {
287                 CT_ERROR("no mount point specified\n");
288                 return -EINVAL;
289         }
290
291         opt.o_mnt = argv[optind];
292
293         CT_TRACE("action=%d src=%s dst=%s mount_point=%s\n",
294                  opt.o_action, opt.o_src, opt.o_dst, opt.o_mnt);
295
296         if (!opt.o_dry_run && opt.o_hsm_root == NULL) {
297                 CT_ERROR("must specify a HSM root\n");
298                 return -EINVAL;
299         }
300
301         if (opt.o_action == CA_IMPORT) {
302                 if (opt.o_src && opt.o_src[0] == '/') {
303                         CT_ERROR("source path must be relative to HSM root.\n");
304                         return -EINVAL;
305                 }
306
307                 if (opt.o_dst && opt.o_dst[0] != '/') {
308                         CT_ERROR("destination path must be absolute.\n");
309                         return -EINVAL;
310                 }
311         }
312
313         return 0;
314 }
315
316 /* mkdir -p path */
317 static int ct_mkdir_p(const char *path)
318 {
319         char    *saved, *ptr;
320         int      rc;
321
322         ptr = strdup(path);
323         saved = ptr;
324         while (*ptr == '/')
325                 ptr++;
326
327         while ((ptr = strchr(ptr, '/')) != NULL) {
328                 *ptr = '\0';
329                 rc = mkdir(saved, DIR_PERM);
330                 *ptr = '/';
331                 if (rc < 0 && errno != EEXIST) {
332                         CT_ERROR("'%s' mkdir failed (%s)\n", path,
333                                  strerror(errno));
334                         free(saved);
335                         return -errno;
336                 }
337                 ptr++;
338         }
339
340         free(saved);
341
342         return 0;
343 }
344
345 static int ct_save_stripe(int src_fd, const char *src, const char *dst)
346 {
347         char                     lov_file[PATH_MAX];
348         char                     lov_buf[XATTR_SIZE_MAX];
349         struct lov_user_md      *lum;
350         int                      rc;
351         int                      fd;
352         ssize_t                  xattr_size;
353
354         snprintf(lov_file, sizeof(lov_file), "%s.lov", dst);
355         CT_TRACE("saving stripe info of '%s' in %s\n", src, lov_file);
356
357         xattr_size = fgetxattr(src_fd, XATTR_LUSTRE_LOV, lov_buf,
358                                sizeof(lov_buf));
359         if (xattr_size < 0) {
360                 CT_ERROR("'%s' cannot get stripe info on (%s)\n", src,
361                          strerror(errno));
362                 return -errno;
363         }
364
365         lum = (struct lov_user_md *)lov_buf;
366
367         if (lum->lmm_magic == LOV_USER_MAGIC_V1 ||
368             lum->lmm_magic == LOV_USER_MAGIC_V3) {
369                 /* Set stripe_offset to -1 so that it is not interpreted as a
370                  * hint on restore. */
371                 lum->lmm_stripe_offset = -1;
372         }
373
374         fd = open(lov_file, O_TRUNC | O_CREAT | O_WRONLY, FILE_PERM);
375         if (fd < 0) {
376                 CT_ERROR("'%s' cannot open (%s)\n", lov_file, strerror(errno));
377                 return -errno;
378         }
379
380         rc = write(fd, lum, xattr_size);
381         if (rc < 0) {
382                 CT_ERROR("'%s' cannot write %d bytes (%s)\n",
383                          lov_file, xattr_size, strerror(errno));
384                 close(fd);
385                 return -errno;
386         }
387
388         rc = close(fd);
389         if (rc < 0) {
390                 CT_ERROR("'%s' cannot close (%s)\n", lov_file, strerror(errno));
391                 return -errno;
392         }
393
394         return 0;
395 }
396
397 static int ct_load_stripe(const char *src, struct lov_user_md_v3 *lum,
398                           size_t *lum_size)
399 {
400         char     lov_file[PATH_MAX];
401         int      rc;
402         int      fd;
403
404         snprintf(lov_file, sizeof(lov_file), "%s.lov", src);
405         CT_TRACE("reading stripe rules from '%s' for '%s'\n", lov_file, src);
406
407         fd = open(lov_file, O_RDONLY);
408         if (fd < 0) {
409                 CT_ERROR("'%s' cannot open (%s)\n", lov_file, strerror(errno));
410                 return -ENODATA;
411         }
412
413         rc = read(fd, lum, *lum_size);
414         if (rc < 0) {
415                 CT_ERROR("'%s' cannot read %lu bytes (%s)\n", lov_file,
416                          lum_size, strerror(errno));
417                 close(fd);
418                 return -ENODATA;
419         }
420
421         *lum_size = (size_t)rc;
422         close(fd);
423
424         return 0;
425 }
426
427 static int ct_restore_stripe(const char *src, const char *dst, int dst_fd)
428 {
429         int                      rc;
430         char                     lov_buf[XATTR_SIZE_MAX];
431         size_t                   lum_size = sizeof(lov_buf);
432
433         rc = ct_load_stripe(src, (struct lov_user_md_v3 *)lov_buf, &lum_size);
434         if (rc) {
435                 CT_WARN("'%s' cannot get stripe rules (%s), use default\n",
436                         src, strerror(-rc));
437                 return 0;
438         }
439
440         rc = fsetxattr(dst_fd, XATTR_LUSTRE_LOV, lov_buf, lum_size, XATTR_CREATE);
441         if (rc < 0) {
442                 CT_ERROR("'%s' cannot set striping (%s)\n",
443                          dst, strerror(errno));
444                 return -errno;
445         }
446
447         return 0;
448 }
449
450 /* non-blocking read or write */
451 static int nonblock_rw(bool wr, int fd, char *buf, int size)
452 {
453         int rc;
454
455         if (wr)
456                 rc = write(fd, buf, size);
457         else
458                 rc = read(fd, buf, size);
459
460         if ((rc < 0) && (errno == -EAGAIN)) {
461                 fd_set set;
462                 struct timeval timeout;
463
464                 timeout.tv_sec = opt.o_report_int;
465
466                 FD_ZERO(&set);
467                 FD_SET(fd, &set);
468                 if (wr)
469                         rc = select(FD_SETSIZE, NULL, &set, NULL, &timeout);
470                 else
471                         rc = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
472                 if (rc < 0)
473                         return -errno;
474                 if (rc == 0)
475                         /* Timed out, we read nothing */
476                         return -EAGAIN;
477
478                 /* Should be available now */
479                 if (wr)
480                         rc = write(fd, buf, size);
481                 else
482                         rc = read(fd, buf, size);
483         }
484
485         if (rc < 0)
486                 rc = -errno;
487
488         return rc;
489 }
490
491 static int ct_copy_data(struct hsm_copyaction_private *hcp, const char *src,
492                         const char *dst, int src_fd, int dst_fd,
493                         const struct hsm_action_item *hai, long hal_flags)
494 {
495         struct hsm_extent        he;
496         struct stat              src_st;
497         struct stat              dst_st;
498         char                    *buf;
499         __u64                    wpos = 0;
500         __u64                    rpos = 0;
501         __u64                    rlen;
502         time_t                   last_print_time = time(0);
503         int                      rsize;
504         int                      wsize;
505         int                      bufoff = 0;
506         int                      rc = 0;
507
508         CT_TRACE("going to copy data from '%s' to %s\n", src, dst);
509
510         buf = malloc(opt.o_chunk_size);
511         if (buf == NULL)
512                 return -ENOMEM;
513
514         if (fstat(src_fd, &src_st) < 0) {
515                 CT_ERROR("'%s' stat failed (%s)\n", src, strerror(errno));
516                 return -errno;
517         }
518
519         if (!S_ISREG(src_st.st_mode)) {
520                 CT_ERROR("'%s' not a regular file\n", src);
521                 return -EINVAL;
522         }
523
524         rc = lseek(src_fd, hai->hai_extent.offset, SEEK_SET);
525         if (rc < 0) {
526                 CT_ERROR("'%s' seek to read to "LPU64" (len %zu)"
527                          " failed (%s)\n",
528                          src, hai->hai_extent.offset, src_st.st_size,
529                          strerror(errno));
530                 rc = -errno;
531                 goto out;
532         }
533
534         if (fstat(dst_fd, &dst_st) < 0) {
535                 CT_ERROR("'%s' stat failed (%s)\n", dst, strerror(errno));
536                 return -errno;
537         }
538
539         if (!S_ISREG(dst_st.st_mode)) {
540                 CT_ERROR("'%s' not a regular file\n", dst);
541                 return -EINVAL;
542         }
543
544         rc = lseek(dst_fd, hai->hai_extent.offset, SEEK_SET);
545         if (rc < 0) {
546                 CT_ERROR("'%s' seek to write to "LPU64" failed (%s)\n", src,
547                          hai->hai_extent.offset, strerror(errno));
548                 rc = -errno;
549                 goto out;
550         }
551
552         he.offset = hai->hai_extent.offset;
553         he.length = 0;
554         rc = llapi_hsm_action_progress(hcp, &he, 0);
555         if (rc) {
556                 /* Action has been canceled or something wrong
557                  * is happening. Stop copying data. */
558                 CT_ERROR("%s->'%s' progress returned err %d\n", src, dst, rc);
559                 goto out;
560         }
561
562         errno = 0;
563         /* Don't read beyond a given extent */
564         rlen = (hai->hai_extent.length == -1LL) ?
565                 src_st.st_size : hai->hai_extent.length;
566
567         while (wpos < rlen) {
568                 int chunk = (rlen - wpos > opt.o_chunk_size) ?
569                             opt.o_chunk_size : rlen - wpos;
570
571                 /* Only read more if we wrote everything in the buffer */
572                 if (wpos == rpos) {
573                         rsize = nonblock_rw(0, src_fd, buf, chunk);
574                         if (rsize == 0)
575                                 /* EOF */
576                                 break;
577
578                         if (rsize == -EAGAIN) {
579                                 /* Timed out */
580                                 rsize = 0;
581                                 if (rpos == 0) {
582                                         /* Haven't read anything yet, let's
583                                          * give it back to the coordinator
584                                          * for rescheduling */
585                                         rc = -EAGAIN;
586                                         break;
587                                 }
588                         }
589
590                         if (rsize < 0) {
591                                 CT_ERROR("'%s' read failed (%s)\n", src,
592                                          strerror(-rsize));
593                                 rc = rsize;
594                                 break;
595                         }
596
597                         rpos += rsize;
598                         bufoff = 0;
599                 }
600
601                 wsize = nonblock_rw(1, dst_fd, buf + bufoff, rpos - wpos);
602                 if (wsize == -EAGAIN)
603                         /* Timed out */
604                         wsize = 0;
605
606                 if (wsize < 0) {
607                         CT_ERROR("'%s' write failed (%s)\n", dst,
608                                  strerror(-wsize));
609                         rc = wsize;
610                         break;
611                 }
612
613                 wpos += wsize;
614                 bufoff += wsize;
615
616                 if (opt.o_bandwidth != 0) {
617                         static unsigned long long       tot_bytes;
618                         static time_t                   start_time, last_time;
619                         time_t                          now = time(0);
620                         double                          tot_time, excess;
621                         unsigned int                    sleep_time;
622
623                         if (now > last_time + 5) {
624                                 tot_bytes = 0;
625                                 start_time = last_time = now;
626                         }
627
628                         tot_bytes += wsize;
629                         tot_time = now - start_time;
630                         if (tot_time < 1)
631                                 tot_time = 1;
632
633                         excess = tot_bytes - tot_time * opt.o_bandwidth;
634                         sleep_time = excess * 1000000 / opt.o_bandwidth;
635                         if ((now - start_time) % 10 == 1)
636                                 CT_TRACE("bandwith control: excess=%E"
637                                          " sleep for %dus\n",
638                                          excess, sleep_time);
639
640                         if (excess > 0)
641                                 usleep(sleep_time);
642
643                         last_time = now;
644                 }
645
646                 if (time(0) >= last_print_time + opt.o_report_int) {
647                         last_print_time = time(0);
648                         CT_TRACE("%%"LPU64" ", 100 * wpos / rlen);
649                         he.length = wpos;
650                         rc = llapi_hsm_action_progress(hcp, &he, 0);
651                         if (rc) {
652                                 /* Action has been canceled or something wrong
653                                  * is happening. Stop copying data. */
654                                 CT_ERROR("%s->'%s' progress returned err %d\n",
655                                          src, dst, rc);
656                                 goto out;
657                         }
658                 }
659                 rc = 0;
660         }
661         CT_TRACE("\n");
662
663 out:
664         /*
665          * truncate restored file
666          * size is taken from the archive this is done to support
667          * restore after a force release which leaves the file with the
668          * wrong size (can big bigger than the new size)
669          */
670         if ((hai->hai_action == HSMA_RESTORE) &&
671             (src_st.st_size < dst_st.st_size)) {
672                 /*
673                  * make sure the file is on disk before reporting success.
674                  */
675                 rc = ftruncate(dst_fd, src_st.st_size);
676                 if (rc < 0) {
677                         rc = -errno;
678                         CT_ERROR("'%s' final truncate to %lu failed (%s)\n",
679                                  dst, src_st.st_size, strerror(-rc));
680                         err_major++;
681                 }
682         }
683
684         if (rc == 0) {
685                 rc = fsync(dst_fd);
686                 if (rc < 0) {
687                         rc = -errno;
688                         CT_ERROR("'%s' fsync failed (%s)\n", dst,
689                                  strerror(-rc));
690                         err_major++;
691                 }
692         }
693
694         free(buf);
695
696         return rc;
697 }
698
699 /* Copy file attributes from file src to file dest */
700 static int ct_copy_attr(const char *src, const char *dst, int src_fd,
701                         int dst_fd)
702 {
703         struct stat     st;
704         struct timeval  times[2];
705
706         if (fstat(src_fd, &st) < 0) {
707                 CT_ERROR("'%s' stat failed (%s)\n",
708                      src, strerror(errno));
709                 return -errno;
710         }
711
712         times[0].tv_sec = st.st_atime;
713         times[0].tv_usec = 0;
714         times[1].tv_sec = st.st_mtime;
715         times[1].tv_usec = 0;
716         if (fchmod(dst_fd, st.st_mode) < 0 ||
717             fchown(dst_fd, st.st_uid, st.st_gid) < 0 ||
718             futimes(dst_fd, times) < 0)
719                 CT_ERROR("'%s' fchmod fchown or futimes failed (%s)\n", src,
720                          strerror(errno));
721                 return -errno;
722         return 0;
723 }
724
725 static int ct_copy_xattr(const char *src, const char *dst, int src_fd,
726                          int dst_fd, bool is_restore)
727 {
728         char     list[XATTR_LIST_MAX];
729         char     value[XATTR_SIZE_MAX];
730         char    *name;
731         ssize_t  list_len;
732         int      rc;
733
734         list_len = flistxattr(src_fd, list, sizeof(list));
735         if (list_len < 0)
736                 return -errno;
737
738         name = list;
739         while (name < list + list_len) {
740                 rc = fgetxattr(src_fd, name, value, sizeof(value));
741                 if (rc < 0)
742                         return -errno;
743
744                 /* when we restore, we do not restore lustre xattr */
745                 if (!is_restore ||
746                     (strncmp(XATTR_TRUSTED_PREFIX, name,
747                              sizeof(XATTR_TRUSTED_PREFIX) - 1) != 0)) {
748                         rc = fsetxattr(dst_fd, name, value, rc, 0);
749                         CT_TRACE("'%s' fsetxattr of '%s' rc=%d (%s)\n",
750                                  dst, name, rc, strerror(errno));
751                         /* lustre.* attrs aren't supported on other FS's */
752                         if (rc < 0 && errno != EOPNOTSUPP) {
753                                 CT_ERROR("'%s' fsetxattr of '%s' failed (%s)\n",
754                                          dst, name, strerror(errno));
755                                 return -errno;
756                         }
757                 }
758                 name += strlen(name) + 1;
759         }
760
761         return 0;
762 }
763
764 static int ct_path_lustre(char *buf, int sz, const char *mnt,
765                           const lustre_fid *fid)
766 {
767         return snprintf(buf, sz, "%s/%s/fid/"DFID_NOBRACE, mnt,
768                         dot_lustre_name, PFID(fid));
769 }
770
771 static int ct_path_archive(char *buf, int sz, const char *archive_dir,
772                            const lustre_fid *fid)
773 {
774         return snprintf(buf, sz, "%s/%04x/%04x/%04x/%04x/%04x/%04x/"
775                         DFID_NOBRACE, archive_dir,
776                         (fid)->f_oid       & 0xFFFF,
777                         (fid)->f_oid >> 16 & 0xFFFF,
778                         (unsigned int)((fid)->f_seq       & 0xFFFF),
779                         (unsigned int)((fid)->f_seq >> 16 & 0xFFFF),
780                         (unsigned int)((fid)->f_seq >> 32 & 0xFFFF),
781                         (unsigned int)((fid)->f_seq >> 48 & 0xFFFF),
782                         PFID(fid));
783 }
784
785 static bool ct_is_retryable(int err)
786 {
787         return err == -ETIMEDOUT;
788 }
789
790 static int ct_begin(struct hsm_copyaction_private **phcp,
791                     const struct hsm_action_item *hai)
792 {
793         char     src[PATH_MAX];
794         int      rc;
795
796         rc = llapi_hsm_action_begin(phcp, ctdata, hai, false);
797         if (rc < 0) {
798                 ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_fid);
799                 CT_ERROR("'%s' copy start failed (%s)\n", src, strerror(-rc));
800         }
801
802         return rc;
803 }
804
805 static int ct_fini(struct hsm_copyaction_private **phcp,
806                    const struct hsm_action_item *hai, int flags, int ct_rc)
807 {
808         char    lstr[PATH_MAX];
809         int     rc;
810
811         CT_TRACE("Action completed, notifying coordinator "
812                  "cookie="LPX64", FID="DFID", flags=%d err=%d\n",
813                  hai->hai_cookie, PFID(&hai->hai_fid),
814                  flags, -ct_rc);
815
816         ct_path_lustre(lstr, sizeof(lstr), opt.o_mnt, &hai->hai_fid);
817         rc = llapi_hsm_action_end(phcp, &hai->hai_extent, flags, abs(ct_rc));
818         if (rc == -ECANCELED)
819                 CT_ERROR("'%s' completed action has been canceled: "
820                          "cookie="LPX64", FID="DFID"\n", lstr, hai->hai_cookie,
821                          PFID(&hai->hai_fid));
822         else if (rc < 0)
823                 CT_ERROR("'%s' copy end failed (%s)\n", lstr, strerror(-rc));
824         else
825                 CT_TRACE("'%s' copy end ok (rc=%d)\n", lstr, rc);
826
827         return rc;
828 }
829
830 static int ct_archive(const struct hsm_action_item *hai, const long hal_flags)
831 {
832         struct hsm_copyaction_private   *hcp = NULL;
833         char                             src[PATH_MAX];
834         char                             dst[PATH_MAX];
835         int                              rc;
836         int                              rcf = 0;
837         bool                             rename_needed = false;
838         int                              ct_flags = 0;
839         int                              open_flags;
840         int                              src_fd = -1;
841         int                              dst_fd = -1;
842
843         rc = ct_begin(&hcp, hai);
844         if (rc < 0)
845                 goto fini_major;
846
847         /* we fill archive so:
848          * source = data FID
849          * destination = lustre FID
850          */
851         ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_dfid);
852         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
853         if (hai->hai_extent.length == -1) {
854                 /* whole file, write it to tmp location and atomically
855                  * replace old archived file */
856                 strncat(dst, "_tmp", sizeof(dst) - strlen(dst) - 1);
857                 /* we cannot rely on the same test because ct_copy_data()
858                  * updates hai_extent.length */
859                 rename_needed = true;
860         }
861
862         CT_TRACE("'%s' archived to %s\n", src, dst);
863
864         if (opt.o_dry_run) {
865                 rc = 0;
866                 goto fini_major;
867         }
868
869         rc = ct_mkdir_p(dst);
870         if (rc < 0) {
871                 CT_ERROR("'%s' mkdir_p failed (%s)\n", dst, strerror(-rc));
872                 goto fini_major;
873         }
874
875         src_fd = open(src, O_RDONLY | O_NOATIME | O_NONBLOCK | O_NOFOLLOW);
876         if (src_fd == -1) {
877                 CT_ERROR("'%s' open read failed (%s)\n", src, strerror(errno));
878                 rc = -errno;
879                 goto fini_major;
880         }
881
882         open_flags = O_WRONLY | O_NOFOLLOW | O_NONBLOCK;
883         /* If extent is specified, don't truncate an old archived copy */
884         open_flags |= ((hai->hai_extent.length == -1) ? O_TRUNC : 0) | O_CREAT;
885
886         dst_fd = open(dst, open_flags, FILE_PERM);
887         if (dst_fd == -1) {
888                 CT_ERROR("'%s' open write failed (%s)\n", dst, strerror(errno));
889                 rc = -errno;
890                 goto fini_major;
891         }
892
893         /* saving stripe is not critical */
894         rc = ct_save_stripe(src_fd, src, dst);
895         if (rc < 0)
896                 CT_ERROR("'%s' cannot save file striping info in '%s' (%s)\n",
897                          src, dst, strerror(-rc));
898
899         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
900         if (rc < 0) {
901                 CT_ERROR("'%s' data copy failed to '%s' (%s)\n",
902                          src, dst, strerror(-rc));
903                 goto fini_major;
904         }
905
906         CT_TRACE("'%s' data archived to '%s' done\n", src, dst);
907
908         /* attrs will remain on the MDS; no need to copy them, except possibly
909           for disaster recovery */
910         if (opt.o_copy_attrs) {
911                 rc = ct_copy_attr(src, dst, src_fd, dst_fd);
912                 if (rc < 0) {
913                         CT_ERROR("'%s' attr copy failed to '%s' (%s)\n",
914                                  src, dst, strerror(-rc));
915                         rcf = rc;
916                 }
917                 CT_TRACE("'%s' attr file copied to archive '%s'\n",
918                          src, dst);
919         }
920
921         /* xattrs will remain on the MDS; no need to copy them, except possibly
922          for disaster recovery */
923         if (opt.o_copy_xattrs) {
924                 rc = ct_copy_xattr(src, dst, src_fd, dst_fd, false);
925                 if (rc < 0) {
926                         CT_ERROR("'%s' xattr copy failed to '%s' (%s)\n",
927                                  src, dst, strerror(-rc));
928                         rcf = rcf ? rcf : rc;
929                 }
930                 CT_ERROR("'%s' xattr file copied to archive '%s'\n",
931                          src, dst);
932         }
933
934         if (rename_needed == true) {
935                 char     tmp_src[PATH_MAX];
936                 char     tmp_dst[PATH_MAX];
937
938                 /* atomically replace old archived file */
939                 ct_path_archive(src, sizeof(src), opt.o_hsm_root,
940                                 &hai->hai_fid);
941                 rc = rename(dst, src);
942                 if (rc < 0) {
943                         CT_ERROR("'%s' renamed to '%s' failed (%s)\n", dst, src,
944                                  strerror(errno));
945                         rc = -errno;
946                         goto fini_major;
947                 }
948                 /* rename lov file */
949                 snprintf(tmp_src, sizeof(tmp_src), "%s.lov", src);
950                 snprintf(tmp_dst, sizeof(tmp_dst), "%s.lov", dst);
951                 rc = rename(tmp_dst, tmp_src);
952                 if (rc < 0)
953                         CT_ERROR("'%s' renamed to '%s' failed (%s)\n",
954                                  tmp_dst, tmp_src, strerror(errno));
955         }
956
957         if (opt.o_shadow_tree) {
958                 /* Create a namespace of softlinks that shadows the original
959                  * Lustre namespace.  This will only be current at
960                  * time-of-archive (won't follow renames).
961                  * WARNING: release won't kill these links; a manual
962                  * cleanup of dead links would be required.
963                  */
964                 char             buf[PATH_MAX];
965                 long long        recno = -1;
966                 int              linkno = 0;
967                 char            *ptr;
968                 int              depth = 0;
969                 int              sz;
970
971                 sprintf(buf, DFID, PFID(&hai->hai_fid));
972                 sprintf(src, "%s/shadow/", opt.o_hsm_root);
973
974                 ptr = opt.o_hsm_root;
975                 while (*ptr)
976                         (*ptr++ == '/') ? depth-- : 0;
977
978                 rc = llapi_fid2path(opt.o_mnt, buf, src + strlen(src),
979                                     sizeof(src) - strlen(src), &recno, &linkno);
980                 if (rc < 0) {
981                         CT_ERROR("'%s' fid2path failed (%s)\n", buf,
982                                  strerror(-rc));
983                         rcf = rcf ? rcf : rc;
984                         goto fini_minor;
985                 }
986
987                 /* Figure out how many parent dirs to symlink back */
988                 ptr = src;
989                 while (*ptr)
990                         (*ptr++ == '/') ? depth++ : 0;
991                 sprintf(buf, "..");
992                 while (--depth > 1)
993                         strcat(buf, "/..");
994
995                 ct_path_archive(dst, sizeof(dst), buf, &hai->hai_fid);
996
997                 if (ct_mkdir_p(src)) {
998                         CT_ERROR("'%s' mkdir_p failed (%s)\n", src,
999                                  strerror(errno));
1000                         rcf = rcf ? rcf : -errno;
1001                         goto fini_minor;
1002                 }
1003                 /* symlink already exists ? */
1004                 sz = readlink(src, buf, sizeof(buf));
1005                 if (sz >= 0) {
1006                         buf[sz] = '\0';
1007                         if (sz == 0 || strncmp(buf, dst, sz) != 0) {
1008                                 if (unlink(src) && errno != ENOENT) {
1009                                         CT_ERROR("'%s' unlink symlink failed "
1010                                                  "(%s)\n", src,
1011                                                  strerror(errno));
1012                                         rcf = rcf ? rcf : -errno;
1013                                         goto fini_minor;
1014                                 /* unlink old symlink done */
1015                                 CT_TRACE("'%s' remove old symlink pointing"
1016                                          " to '%s'\n", src, buf);
1017                                 }
1018                         } else {
1019                                 /* symlink already ok */
1020                                 CT_TRACE("'%s' symlink already pointing"
1021                                          " to '%s'\n", src, dst);
1022                                 rcf = 0;
1023                                 goto fini_minor;
1024                         }
1025                 }
1026                 if (symlink(dst, src)) {
1027                         CT_ERROR("'%s' symlink to '%s' failed (%s)\n", src, dst,
1028                                  strerror(errno));
1029                         rcf = rcf ? rcf : -errno;
1030                         goto fini_minor;
1031                 }
1032                 CT_TRACE("'%s' symlink to '%s' done\n", src, dst);
1033         }
1034 fini_minor:
1035         if (rcf)
1036                 err_minor++;
1037         goto out;
1038
1039
1040 fini_major:
1041         err_major++;
1042
1043         unlink(dst);
1044         if (ct_is_retryable(rc))
1045                 ct_flags |= HP_FLAG_RETRY;
1046
1047         rcf = rc;
1048
1049 out:
1050         if (!(src_fd < 0))
1051                 close(src_fd);
1052
1053         if (!(dst_fd < 0))
1054                 close(dst_fd);
1055
1056         if (hcp != NULL)
1057                 rc = ct_fini(&hcp, hai, ct_flags, rcf);
1058
1059         return rc;
1060 }
1061
1062 static int ct_restore(const struct hsm_action_item *hai, const long hal_flags)
1063 {
1064         struct hsm_copyaction_private   *hcp = NULL;
1065         char                             src[PATH_MAX];
1066         char                             dst[PATH_MAX];
1067         int                              rc;
1068         int                              flags = 0;
1069         int                              src_fd = -1;
1070         int                              dst_fd = -1;
1071         lustre_fid                       dfid;
1072
1073         rc = ct_begin(&hcp, hai);
1074         if (rc)
1075                 goto fini;
1076
1077         /* we fill lustre so:
1078          * source = lustre FID in the backend
1079          * destination = data FID = volatile file
1080          */
1081
1082         /* build backend file name from released file FID */
1083         ct_path_archive(src, sizeof(src), opt.o_hsm_root, &hai->hai_fid);
1084
1085         /* get the FID of the volatile file */
1086         rc = llapi_hsm_action_get_dfid(hcp, &dfid);
1087         if (rc < 0) {
1088                 CT_ERROR("restoring "DFID", cannot get FID of created volatile"
1089                          " file (%s)\n", PFID(&hai->hai_fid), strerror(-rc));
1090                 goto fini;
1091         }
1092
1093         /* build volatile "file name", for messages */
1094         snprintf(dst, sizeof(dst), "{VOLATILE}="DFID, PFID(&dfid));
1095
1096         CT_TRACE("'%s' restore data to '%s'\n", src, dst);
1097
1098         if (opt.o_dry_run) {
1099                 rc = 0;
1100                 goto fini;
1101         }
1102
1103         src_fd = open(src, O_RDONLY | O_NOATIME | O_NONBLOCK | O_NOFOLLOW);
1104         if (src_fd < 0) {
1105                 CT_ERROR("'%s' open for read failed (%s)\n", src,
1106                          strerror(errno));
1107                 rc = -errno;
1108                 goto fini;
1109         }
1110
1111         dst_fd = llapi_hsm_action_get_fd(hcp);
1112
1113         /* the layout cannot be allocated through .fid so we have to
1114          * restore a layout */
1115         rc = ct_restore_stripe(src, dst, dst_fd);
1116         if (rc) {
1117                 CT_ERROR("'%s' cannot restore file striping info from '%s'"
1118                          " (%s)\n", dst, src, strerror(-rc));
1119                 err_major++;
1120                 goto fini;
1121         }
1122
1123         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
1124         if (rc < 0) {
1125                 CT_ERROR("'%s' data copy to '%s' failed (%s)\n", src, dst,
1126                          strerror(-rc));
1127                 err_major++;
1128                 if (ct_is_retryable(rc))
1129                         flags |= HP_FLAG_RETRY;
1130                 goto fini;
1131         }
1132
1133         CT_TRACE("'%s' data restore done to %s\n", src, dst);
1134
1135 fini:
1136         if (hcp != NULL)
1137                 rc = ct_fini(&hcp, hai, flags, rc);
1138
1139         /* object swaping is done by cdt at copy end, so close of volatile file
1140          * cannot be done before */
1141         if (!(src_fd < 0))
1142                 close(src_fd);
1143
1144         if (!(dst_fd < 0))
1145                 close(dst_fd);
1146
1147         return rc;
1148 }
1149
1150 static int ct_remove(const struct hsm_action_item *hai, const long hal_flags)
1151 {
1152         struct hsm_copyaction_private   *hcp = NULL;
1153         char                             dst[PATH_MAX];
1154         int                              rc;
1155
1156         rc = ct_begin(&hcp, hai);
1157         if (rc < 0)
1158                 goto fini;
1159
1160         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
1161
1162         CT_TRACE("'%s' removed file\n", dst);
1163
1164         if (opt.o_dry_run) {
1165                 rc = 0;
1166                 goto fini;
1167         }
1168
1169         rc = unlink(dst);
1170         if (rc < 0) {
1171                 rc = -errno;
1172                 CT_ERROR("'%s' unlink failed (%s)\n", dst, strerror(-rc));
1173                 err_minor++;
1174                 goto fini;
1175         }
1176
1177 fini:
1178         if (hcp != NULL)
1179                 rc = ct_fini(&hcp, hai, 0, rc);
1180
1181         return rc;
1182 }
1183
1184 static int ct_report_error(const struct hsm_action_item *hai, int flags,
1185                            int errval)
1186 {
1187         struct hsm_copyaction_private   *hcp;
1188         int                              rc;
1189
1190         rc = llapi_hsm_action_begin(&hcp, ctdata, hai, true);
1191         if (rc)
1192                 return rc;
1193
1194         rc = llapi_hsm_action_end(&hcp, &hai->hai_extent, flags, abs(errval));
1195
1196         return rc;
1197 }
1198
1199 static int ct_process_item(struct hsm_action_item *hai, const long hal_flags)
1200 {
1201         int     rc = 0;
1202
1203         if (opt.o_verbose >= LLAPI_MSG_INFO || opt.o_dry_run) {
1204                 /* Print the original path */
1205                 char            fid[128];
1206                 char            path[PATH_MAX];
1207                 long long       recno = -1;
1208                 int             linkno = 0;
1209
1210                 sprintf(fid, DFID, PFID(&hai->hai_fid));
1211                 CT_TRACE("'%s' action %s reclen %d, cookie="LPX64"\n",
1212                          fid, hsm_copytool_action2name(hai->hai_action),
1213                          hai->hai_len, hai->hai_cookie);
1214                 rc = llapi_fid2path(opt.o_mnt, fid, path,
1215                                     sizeof(path), &recno, &linkno);
1216                 if (rc < 0)
1217                         CT_ERROR("'%s' fid2path failed (%s)\n", fid,
1218                                  strerror(-rc));
1219                 else
1220                         CT_TRACE("'%s' processing file\n", path);
1221         }
1222
1223         switch (hai->hai_action) {
1224         /* set err_major, minor inside these functions */
1225         case HSMA_ARCHIVE:
1226                 rc = ct_archive(hai, hal_flags);
1227                 break;
1228         case HSMA_RESTORE:
1229                 rc = ct_restore(hai, hal_flags);
1230                 break;
1231         case HSMA_REMOVE:
1232                 rc = ct_remove(hai, hal_flags);
1233                 break;
1234         case HSMA_CANCEL:
1235                 CT_TRACE("'%s' cancel not implemented\n", opt.o_mnt);
1236                 /* Don't report progress to coordinator for this cookie:
1237                  * the copy function will get ECANCELED when reporting
1238                  * progress. */
1239                 err_minor++;
1240                 return 0;
1241                 break;
1242         default:
1243                 CT_ERROR("'%s' unknown action %d\n", opt.o_mnt,
1244                          hai->hai_action);
1245                 err_minor++;
1246                 ct_report_error(hai, 0, -EINVAL);
1247         }
1248
1249         return 0;
1250 }
1251
1252 struct ct_th_data {
1253         long                     hal_flags;
1254         struct hsm_action_item  *hai;
1255 };
1256
1257 static void *ct_thread(void *data)
1258 {
1259         struct ct_th_data *cttd = data;
1260         int rc;
1261
1262         rc = ct_process_item(cttd->hai, cttd->hal_flags);
1263
1264         free(cttd->hai);
1265         free(cttd);
1266         pthread_exit((void *)(intptr_t)rc);
1267 }
1268
1269 static int ct_process_item_async(const struct hsm_action_item *hai,
1270                                  long hal_flags)
1271 {
1272         pthread_attr_t           attr;
1273         pthread_t                thread;
1274         struct ct_th_data       *data;
1275         int                      rc;
1276
1277         data = malloc(sizeof(*data));
1278         if (data == NULL)
1279                 return -ENOMEM;
1280
1281         data->hai = malloc(hai->hai_len);
1282         if (data->hai == NULL) {
1283                 free(data);
1284                 return -ENOMEM;
1285         }
1286
1287         memcpy(data->hai, hai, hai->hai_len);
1288         data->hal_flags = hal_flags;
1289
1290         rc = pthread_attr_init(&attr);
1291         if (rc != 0) {
1292                 CT_ERROR("'%s' pthread_attr_init: %s\n", opt.o_mnt,
1293                          strerror(rc));
1294                 free(data->hai);
1295                 free(data);
1296                 return -rc;
1297         }
1298
1299         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1300
1301         rc = pthread_create(&thread, &attr, ct_thread, data);
1302         if (rc != 0)
1303                 CT_ERROR("'%s' thread create: (%s)\n", opt.o_mnt, strerror(rc));
1304
1305         pthread_attr_destroy(&attr);
1306         return 0;
1307 }
1308
1309 static int ct_import_one(const char *src, const char *dst)
1310 {
1311         char            newarc[PATH_MAX];
1312         lustre_fid      fid;
1313         struct stat     st;
1314         int             rc;
1315
1316         CT_TRACE("'%s' importing from %s\n", dst, src);
1317
1318         if (stat(src, &st) < 0) {
1319                 CT_ERROR("'%s' stat failed (%s)\n", src, strerror(errno));
1320                 return -errno;
1321         }
1322
1323         if (opt.o_dry_run)
1324                 return 0;
1325
1326         rc = llapi_hsm_import(dst,
1327                               opt.o_archive_cnt ? opt.o_archive_id[0] : 0,
1328                               &st, 0, 0, 0, 0, NULL, &fid);
1329         if (rc < 0) {
1330                 CT_ERROR("'%s' import from '%s' failed (%s)\n", dst, src,
1331                          strerror(-rc));
1332                 return -rc;
1333         }
1334
1335         ct_path_archive(newarc, sizeof(newarc), opt.o_hsm_root, &fid);
1336
1337         rc = ct_mkdir_p(newarc);
1338         if (rc < 0) {
1339                 CT_ERROR("'%s' mkdir_p failed (%s)\n", newarc, strerror(-rc));
1340                 err_major++;
1341                 return rc;
1342
1343         }
1344
1345         /* Lots of choices now: mv, ln, ln -s ? */
1346         rc = link(src, newarc); /* hardlink */
1347         if (rc < 0) {
1348                 CT_ERROR("'%s' link to '%s' failed (%s)\n", newarc, src,
1349                          strerror(errno));
1350                 err_major++;
1351                 return -errno;
1352         }
1353         CT_TRACE("'%s' imported from '%s'=='%s'\n", dst, newarc, src);
1354
1355         return 0;
1356 }
1357
1358 static char *path_concat(const char *dirname, const char *basename)
1359 {
1360         char    *result;
1361         int      dirlen = strlen(dirname);
1362
1363         result = malloc(dirlen + strlen(basename) + 2);
1364         if (result == NULL)
1365                 return NULL;
1366
1367         memcpy(result, dirname, dirlen);
1368         result[dirlen] = '/';
1369         strcpy(result + dirlen + 1, basename);
1370
1371         return result;
1372 }
1373
1374 static int ct_import_recurse(const char *relpath)
1375 {
1376         DIR             *dir;
1377         struct dirent    ent, *cookie = NULL;
1378         char            *srcpath, *newpath;
1379         int              rc;
1380
1381         if (relpath == NULL)
1382                 return -EINVAL;
1383
1384         srcpath = path_concat(opt.o_hsm_root, relpath);
1385         if (srcpath == NULL) {
1386                 err_major++;
1387                 return -ENOMEM;
1388         }
1389
1390         dir = opendir(srcpath);
1391         if (dir == NULL) {
1392                 /* Not a dir, or error */
1393                 if (errno == ENOTDIR) {
1394                         /* Single regular file case, treat o_dst as absolute
1395                            final location. */
1396                         rc = ct_import_one(srcpath, opt.o_dst);
1397                 } else {
1398                         CT_ERROR("'%s' opendir failed (%s)\n", srcpath,
1399                                  strerror(errno));
1400                         err_major++;
1401                         rc = -errno;
1402                 }
1403                 free(srcpath);
1404                 return rc;
1405         }
1406         free(srcpath);
1407
1408         while (1) {
1409                 rc = readdir_r(dir, &ent, &cookie);
1410                 if (rc != 0) {
1411                         CT_ERROR("'%s' readdir_r failed (%s)\n", relpath,
1412                                  strerror(errno));
1413                         err_major++;
1414                         rc = -errno;
1415                         goto out;
1416                 } else if ((rc == 0) && (cookie == NULL)) {
1417                         /* end of directory */
1418                         break;
1419                 }
1420
1421                 if (!strcmp(ent.d_name, ".") ||
1422                     !strcmp(ent.d_name, ".."))
1423                         continue;
1424
1425                 /* New relative path */
1426                 newpath = path_concat(relpath, ent.d_name);
1427                 if (newpath == NULL) {
1428                         err_major++;
1429                         rc = -ENOMEM;
1430                         goto out;
1431                 }
1432
1433                 if (ent.d_type == DT_DIR) {
1434                         rc = ct_import_recurse(newpath);
1435                 } else {
1436                         char src[PATH_MAX];
1437                         char dst[PATH_MAX];
1438
1439                         sprintf(src, "%s/%s", opt.o_hsm_root, newpath);
1440                         sprintf(dst, "%s/%s", opt.o_dst, newpath);
1441                         /* Make the target dir in the Lustre fs */
1442                         rc = ct_mkdir_p(dst);
1443                         if (rc == 0) {
1444                                 /* Import the file */
1445                                 rc = ct_import_one(src, dst);
1446                         } else {
1447                                 CT_ERROR("'%s' ct_mkdir_p failed (%s)\n", dst,
1448                                          strerror(-rc));
1449                                 err_major++;
1450                         }
1451                 }
1452
1453                 if (rc != 0) {
1454                         CT_ERROR("'%s' importing failed\n", newpath);
1455                         if (err_major && opt.o_abort_on_error) {
1456                                 free(newpath);
1457                                 goto out;
1458                         }
1459                 }
1460                 free(newpath);
1461         }
1462
1463         rc = 0;
1464 out:
1465         closedir(dir);
1466         return rc;
1467 }
1468
1469 static int ct_rebind_one(const lustre_fid *old_fid, const lustre_fid *new_fid)
1470 {
1471         char src[PATH_MAX];
1472         char dst[PATH_MAX];
1473
1474         CT_TRACE("rebind "DFID" to "DFID"\n", PFID(old_fid), PFID(new_fid));
1475
1476         ct_path_archive(src, sizeof(src), opt.o_hsm_root, old_fid);
1477         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, new_fid);
1478
1479         if (!opt.o_dry_run) {
1480                 ct_mkdir_p(dst);
1481                 if (rename(src, dst)) {
1482                         CT_ERROR("'%s' rename to '%s' failed (%s)\n", src, dst,
1483                                  strerror(errno));
1484                         return -errno;
1485                 }
1486                 /* rename lov file */
1487                 strncat(src, ".lov", sizeof(src) - strlen(src) - 1);
1488                 strncat(dst, ".lov", sizeof(dst) - strlen(dst) - 1);
1489                 if (rename(src, dst))
1490                         CT_ERROR("'%s' rename to '%s' failed (%s)\n", src, dst,
1491                                  strerror(errno));
1492
1493         }
1494         return 0;
1495 }
1496
1497 static bool fid_is_file(lustre_fid *fid)
1498 {
1499         return fid_is_norm(fid) || fid_is_igif(fid);
1500 }
1501
1502 static bool should_ignore_line(const char *line)
1503 {
1504         int     i;
1505
1506         for (i = 0; line[i] != '\0'; i++) {
1507                 if (isspace(line[i]))
1508                         continue;
1509                 else if (line[i] == '#')
1510                         return true;
1511                 else
1512                         return false;
1513         }
1514
1515         return true;
1516 }
1517
1518 static int ct_rebind_list(const char *list)
1519 {
1520         int              rc;
1521         FILE            *filp;
1522         ssize_t          r;
1523         char            *line = NULL;
1524         size_t           line_size = 0;
1525         unsigned int     nl = 0;
1526         unsigned int     ok = 0;
1527
1528         filp = fopen(list, "r");
1529         if (filp == NULL) {
1530                 CT_ERROR("'%s' open failed (%s)\n", list, strerror(errno));
1531                 return -errno;
1532         }
1533
1534         /* each line consists of 2 FID */
1535         while ((r = getline(&line, &line_size, filp)) != -1) {
1536                 lustre_fid      old_fid;
1537                 lustre_fid      new_fid;
1538
1539                 /* Ignore empty and commented out ('#...') lines. */
1540                 if (should_ignore_line(line))
1541                         continue;
1542
1543                 nl++;
1544
1545                 rc = sscanf(line, SFID" "SFID, RFID(&old_fid), RFID(&new_fid));
1546                 if (rc != 6 || !fid_is_file(&old_fid) ||
1547                     !fid_is_file(&new_fid)) {
1548                         CT_ERROR("'%s' FID expected near '%s', line %u\n",
1549                                  list, line, nl);
1550                         err_major++;
1551                         continue;
1552                 }
1553
1554                 if (ct_rebind_one(&old_fid, &new_fid))
1555                         err_major++;
1556                 else
1557                         ok++;
1558         }
1559
1560         fclose(filp);
1561
1562         if (line)
1563                 free(line);
1564
1565         /* return 0 if all rebinds were sucessful */
1566         CT_TRACE("'%s' %u lines read, %u rebind successful\n", list, nl, ok);
1567
1568         return ok == nl ? 0 : -1;
1569 }
1570
1571 static int ct_rebind(void)
1572 {
1573         int     rc;
1574
1575         if (opt.o_dst) {
1576                 lustre_fid      old_fid;
1577                 lustre_fid      new_fid;
1578
1579                 if (sscanf(opt.o_src, SFID, RFID(&old_fid)) != 3 ||
1580                     !fid_is_file(&old_fid)) {
1581                         CT_ERROR("'%s' invalid FID format\n", opt.o_src);
1582                         return -EINVAL;
1583                 }
1584
1585                 if (sscanf(opt.o_dst, SFID, RFID(&new_fid)) != 3 ||
1586                     !fid_is_file(&new_fid)) {
1587                         CT_ERROR("'%s' invalid FID format\n", opt.o_dst);
1588                         return -EINVAL;
1589                 }
1590
1591                 rc = ct_rebind_one(&old_fid, &new_fid);
1592
1593                 return rc;
1594         }
1595
1596         /* o_src is a list file */
1597         rc = ct_rebind_list(opt.o_src);
1598
1599         return rc;
1600 }
1601
1602 static int ct_dir_level_max(const char *dirpath, __u16 *sub_seqmax)
1603 {
1604         DIR             *dir;
1605         int              rc;
1606         __u16            sub_seq;
1607         struct dirent    ent, *cookie = NULL;
1608
1609         *sub_seqmax = 0;
1610
1611         dir = opendir(dirpath);
1612         if (dir == NULL) {
1613                 rc = -errno;
1614                 CT_ERROR("'%s' failed to open directory (%s)\n", opt.o_hsm_root,
1615                          strerror(-rc));
1616                 return rc;
1617         }
1618
1619         while ((rc = readdir_r(dir, &ent, &cookie)) == 0) {
1620                 if (cookie == NULL)
1621                         /* end of directory.
1622                          * rc is 0 and seqmax contains the max value. */
1623                         goto out;
1624
1625                 if (!strcmp(ent.d_name, ".") || !strcmp(ent.d_name, ".."))
1626                         continue;
1627
1628                 if (sscanf(ent.d_name, "%hx", &sub_seq) != 1) {
1629                         CT_TRACE("'%s' unexpected dirname format, "
1630                                  "skip entry.\n", ent.d_name);
1631                         continue;
1632                 }
1633                 if (sub_seq > *sub_seqmax)
1634                         *sub_seqmax = sub_seq;
1635         }
1636         rc = -errno;
1637         CT_ERROR("'%s' readdir_r failed (%s)\n", dirpath, strerror(-rc));
1638
1639 out:
1640         closedir(dir);
1641         return rc;
1642 }
1643
1644 static int ct_max_sequence(void)
1645 {
1646         int   rc, i;
1647         char  path[PATH_MAX];
1648         __u64 seq = 0;
1649         __u16 subseq;
1650
1651         strncpy(path, opt.o_hsm_root, sizeof(path));
1652         /* FID sequence is stored in top-level directory names:
1653          * hsm_root/16bits (high weight)/16 bits/16 bits/16 bits (low weight).
1654          */
1655         for (i = 0; i < 4; i++) {
1656                 rc = ct_dir_level_max(path, &subseq);
1657                 if (rc != 0)
1658                         return rc;
1659                 seq |= ((__u64)subseq << ((3 - i) * 16));
1660                 sprintf(path + strlen(path), "/%04x", subseq);
1661         }
1662
1663         printf("max_sequence: %016Lx\n", seq);
1664
1665         return 0;
1666 }
1667
1668 static void handler(int signal)
1669 {
1670         psignal(signal, "exiting");
1671         /* If we don't clean up upon interrupt, umount thinks there's a ref
1672          * and doesn't remove us from mtab (EINPROGRESS). The lustre client
1673          * does successfully unmount and the mount is actually gone, but the
1674          * mtab entry remains. So this just makes mtab happier. */
1675         llapi_hsm_copytool_unregister(&ctdata);
1676         _exit(1);
1677 }
1678
1679 /* Daemon waits for messages from the kernel; run it in the background. */
1680 static int ct_daemon(void)
1681 {
1682         int     rc;
1683
1684         rc = daemon(1, 1);
1685         if (rc < 0) {
1686                 CT_ERROR("%d: cannot start as daemon (%s)", getpid(),
1687                          strerror(errno));
1688                 return -errno;
1689         }
1690
1691         rc = llapi_hsm_copytool_register(&ctdata, opt.o_mnt, 0,
1692                                          opt.o_archive_cnt, opt.o_archive_id);
1693         if (rc < 0) {
1694                 CT_ERROR("%d: cannot start copytool interface: %s\n", getpid(),
1695                          strerror(-rc));
1696                 return rc;
1697         }
1698
1699         signal(SIGINT, handler);
1700         signal(SIGTERM, handler);
1701
1702         while (1) {
1703                 struct hsm_action_list  *hal;
1704                 struct hsm_action_item  *hai;
1705                 int                      msgsize;
1706                 int                      i = 0;
1707
1708                 CT_TRACE("%d: waiting for message from kernel\n", getpid());
1709
1710                 rc = llapi_hsm_copytool_recv(ctdata, &hal, &msgsize);
1711                 if (rc == -ESHUTDOWN) {
1712                         CT_TRACE("%d: shutting down", getpid());
1713                         break;
1714                 } else if (rc == -EAGAIN) {
1715                         continue; /* msg not for us */
1716                 } else if (rc < 0) {
1717                         CT_WARN("%d: message receive: (%s)\n", getpid(),
1718                                 strerror(-rc));
1719                         err_major++;
1720                         if (opt.o_abort_on_error)
1721                                 break;
1722                         else
1723                                 continue;
1724                 }
1725
1726                 CT_TRACE("%d: copytool fs=%s archive#=%d item_count=%d\n",
1727                          getpid(), hal->hal_fsname, hal->hal_archive_id,
1728                          hal->hal_count);
1729
1730                 if (strcmp(hal->hal_fsname, fs_name) != 0) {
1731                         CT_ERROR("'%s' invalid fs name, expecting: %s\n",
1732                                  hal->hal_fsname, fs_name);
1733                         err_major++;
1734                         if (opt.o_abort_on_error)
1735                                 break;
1736                         else
1737                                 continue;
1738                 }
1739
1740                 hai = hai_zero(hal);
1741                 while (++i <= hal->hal_count) {
1742                         if ((char *)hai - (char *)hal > msgsize) {
1743                                 CT_ERROR("'%s' item %d past end of message!\n",
1744                                          opt.o_mnt, i);
1745                                 err_major++;
1746                                 rc = -EPROTO;
1747                                 break;
1748                         }
1749                         rc = ct_process_item_async(hai, hal->hal_flags);
1750                         if (rc < 0)
1751                                 CT_ERROR("'%s' item %d process err: %s\n",
1752                                          opt.o_mnt, i, strerror(-rc));
1753                         if (opt.o_abort_on_error && err_major)
1754                                 break;
1755                         hai = hai_next(hai);
1756                 }
1757
1758                 llapi_hsm_action_list_free(&hal);
1759
1760                 if (opt.o_abort_on_error && err_major)
1761                         break;
1762         }
1763
1764         llapi_hsm_copytool_unregister(&ctdata);
1765
1766         return rc;
1767 }
1768
1769 static int ct_setup(void)
1770 {
1771         int     rc;
1772
1773         /* set llapi message level */
1774         llapi_msg_set_level(opt.o_verbose);
1775
1776         arc_fd = open(opt.o_hsm_root, O_DIRECTORY);
1777         if (arc_fd < 0) {
1778                 CT_ERROR("cannot open archive at '%s': %s\n", opt.o_hsm_root,
1779                          strerror(errno));
1780                 return -errno;
1781         }
1782
1783         rc = llapi_search_fsname(opt.o_mnt, fs_name);
1784         if (rc) {
1785                 CT_ERROR("cannot find a Lustre filesystem mounted at: %s\n",
1786                          opt.o_mnt);
1787                 return -rc;
1788         }
1789
1790         return rc;
1791 }
1792
1793 static int ct_cleanup(void)
1794 {
1795         if (arc_fd < 0)
1796                 return 0;
1797
1798         if (close(arc_fd) < 0) {
1799                 CT_ERROR("cannot close archive: %s.\n", strerror(errno));
1800                 return -errno;
1801         }
1802
1803         return 0;
1804 }
1805
1806 int main(int argc, char **argv)
1807 {
1808         int     rc;
1809
1810         strncpy(cmd_name, basename(argv[0]), sizeof(cmd_name));
1811         rc = ct_parseopts(argc, argv);
1812         if (rc) {
1813                 CT_ERROR("try '%s --help' for more information.\n", cmd_name);
1814                 return -rc;
1815         }
1816
1817         ct_setup();
1818
1819         switch (opt.o_action) {
1820         case CA_IMPORT:
1821                 rc = ct_import_recurse(opt.o_src);
1822                 break;
1823         case CA_REBIND:
1824                 rc = ct_rebind();
1825                 break;
1826         case CA_MAXSEQ:
1827                 rc = ct_max_sequence();
1828                 break;
1829         case CA_DAEMON:
1830                 rc = ct_daemon();
1831                 break;
1832         default:
1833                 CT_ERROR("no action specified. Try '%s --help' for more "
1834                          "information.\n", cmd_name);
1835                 rc = -EINVAL;
1836                 break;
1837         }
1838
1839         if (opt.o_action != CA_MAXSEQ)
1840                 CT_TRACE("%s(%d) finished, errs: %d major, %d minor, "
1841                          "rc=%d (%s)\n", argv[0], getpid(), err_major,
1842                          err_minor, rc, strerror(-rc));
1843
1844         ct_cleanup();
1845
1846         return -rc;
1847 }
1848