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