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