Whamcloud - gitweb
40cbf3c6f8cdc06171a3e4e1f78a24c8f62bbad9
[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 ("LPU64" > "
551                          "%jd) of '%s' source file", hai->hai_extent.offset,
552                          (intmax_t)src_st.st_size, src);
553                 return rc;
554         }
555
556         if (fstat(dst_fd, &dst_st) < 0) {
557                 rc = -errno;
558                 CT_ERROR(rc, "cannot stat '%s'", dst);
559                 return rc;
560         }
561
562         if (!S_ISREG(dst_st.st_mode)) {
563                 rc = -EINVAL;
564                 CT_ERROR(rc, "'%s' is not a regular file", dst);
565                 return rc;
566         }
567
568         /* Don't read beyond a given extent */
569         if (length > src_st.st_size - hai->hai_extent.offset)
570                 length = src_st.st_size - hai->hai_extent.offset;
571
572         start_time = last_bw_print = last_report_time = time(NULL);
573
574         he.offset = offset;
575         he.length = 0;
576         rc = llapi_hsm_action_progress(hcp, &he, length, 0);
577         if (rc < 0) {
578                 /* Action has been canceled or something wrong
579                  * is happening. Stop copying data. */
580                 CT_ERROR(rc, "progress ioctl for copy '%s'->'%s' failed",
581                          src, dst);
582                 goto out;
583         }
584
585         errno = 0;
586
587         buf = malloc(opt.o_chunk_size);
588         if (buf == NULL) {
589                 rc = -ENOMEM;
590                 goto out;
591         }
592
593         CT_TRACE("start copy of "LPU64" bytes from '%s' to '%s'",
594                  length, src, dst);
595
596         while (write_total < length) {
597                 ssize_t rsize;
598                 ssize_t wsize;
599                 int     chunk = (length - write_total > opt.o_chunk_size) ?
600                                  opt.o_chunk_size : length - write_total;
601
602                 rsize = pread(src_fd, buf, chunk, offset);
603                 if (rsize == 0)
604                         /* EOF */
605                         break;
606
607                 if (rsize < 0) {
608                         rc = -errno;
609                         CT_ERROR(rc, "cannot read from '%s'", src);
610                         break;
611                 }
612
613                 wsize = pwrite(dst_fd, buf, rsize, offset);
614                 if (wsize < 0) {
615                         rc = -errno;
616                         CT_ERROR(rc, "cannot write to '%s'", dst);
617                         break;
618                 }
619
620                 write_total += wsize;
621                 offset += wsize;
622
623                 now = time(NULL);
624                 /* sleep if needed, to honor bandwidth limits */
625                 if (opt.o_bandwidth != 0) {
626                         unsigned long long write_theory;
627
628                         write_theory = (now - start_time) * opt.o_bandwidth;
629
630                         if (write_theory < write_total) {
631                                 unsigned long long      excess;
632                                 struct timespec         delay;
633
634                                 excess = write_total - write_theory;
635
636                                 delay.tv_sec = excess / opt.o_bandwidth;
637                                 delay.tv_nsec = (excess % opt.o_bandwidth) *
638                                         NSEC_PER_SEC / opt.o_bandwidth;
639
640                                 if (now >= last_bw_print + opt.o_report_int) {
641                                         CT_TRACE("bandwith control: %lluB/s "
642                                                  "excess=%llu sleep for "
643                                                  "%lld.%09lds",
644                                                  opt.o_bandwidth, excess,
645                                                  (long long)delay.tv_sec,
646                                                  delay.tv_nsec);
647                                         last_bw_print = now;
648                                 }
649
650                                 do {
651                                         rc = nanosleep(&delay, &delay);
652                                 } while (rc < 0 && errno == EINTR);
653                                 if (rc < 0) {
654                                         CT_ERROR(errno, "delay for bandwidth "
655                                                  "control failed to sleep: "
656                                                  "residual=%lld.%09lds",
657                                                  (long long)delay.tv_sec,
658                                                  delay.tv_nsec);
659                                         rc = 0;
660                                 }
661                         }
662                 }
663
664                 now = time(NULL);
665                 if (now >= last_report_time + opt.o_report_int) {
666                         last_report_time = now;
667                         CT_TRACE("%%"LPU64" ", 100 * write_total / length);
668                         /* only give the length of the write since the last
669                          * progress report */
670                         he.length = offset - he.offset;
671                         rc = llapi_hsm_action_progress(hcp, &he, length, 0);
672                         if (rc < 0) {
673                                 /* Action has been canceled or something wrong
674                                  * is happening. Stop copying data. */
675                                 CT_ERROR(rc, "progress ioctl for copy"
676                                          " '%s'->'%s' failed", src, dst);
677                                 goto out;
678                         }
679                         he.offset = offset;
680                 }
681                 rc = 0;
682         }
683
684 out:
685         /*
686          * truncate restored file
687          * size is taken from the archive this is done to support
688          * restore after a force release which leaves the file with the
689          * wrong size (can big bigger than the new size)
690          */
691         if ((hai->hai_action == HSMA_RESTORE) &&
692             (src_st.st_size < dst_st.st_size)) {
693                 /*
694                  * make sure the file is on disk before reporting success.
695                  */
696                 rc = ftruncate(dst_fd, src_st.st_size);
697                 if (rc < 0) {
698                         rc = -errno;
699                         CT_ERROR(rc, "cannot truncate '%s' to size %jd",
700                                  dst, (intmax_t)src_st.st_size);
701                         err_major++;
702                 }
703         }
704
705         if (buf != NULL)
706                 free(buf);
707
708         CT_TRACE("copied "LPU64" bytes in %f seconds",
709                  length, ct_now() - start_ct_now);
710
711         return rc;
712 }
713
714 /* Copy file attributes from file src to file dest */
715 static int ct_copy_attr(const char *src, const char *dst, int src_fd,
716                         int dst_fd)
717 {
718         struct stat     st;
719         struct timeval  times[2];
720         int             rc;
721
722         if (fstat(src_fd, &st) < 0) {
723                 rc = -errno;
724                 CT_ERROR(rc, "cannot stat '%s'", src);
725                 return rc;
726         }
727
728         times[0].tv_sec = st.st_atime;
729         times[0].tv_usec = 0;
730         times[1].tv_sec = st.st_mtime;
731         times[1].tv_usec = 0;
732         if (fchmod(dst_fd, st.st_mode) < 0 ||
733             fchown(dst_fd, st.st_uid, st.st_gid) < 0 ||
734             futimes(dst_fd, times) < 0) {
735                 rc = -errno;
736                 CT_ERROR(rc, "cannot set attributes of '%s'", src);
737                 return rc;
738         }
739
740         return 0;
741 }
742
743 static int ct_copy_xattr(const char *src, const char *dst, int src_fd,
744                          int dst_fd, bool is_restore)
745 {
746         char     list[XATTR_LIST_MAX];
747         char     value[XATTR_SIZE_MAX];
748         char    *name;
749         ssize_t  list_len;
750         int      rc;
751
752         list_len = flistxattr(src_fd, list, sizeof(list));
753         if (list_len < 0)
754                 return -errno;
755
756         name = list;
757         while (name < list + list_len) {
758                 rc = fgetxattr(src_fd, name, value, sizeof(value));
759                 if (rc < 0)
760                         return -errno;
761
762                 /* when we restore, we do not restore lustre xattr */
763                 if (!is_restore ||
764                     (strncmp(XATTR_TRUSTED_PREFIX, name,
765                              sizeof(XATTR_TRUSTED_PREFIX) - 1) != 0)) {
766                         rc = fsetxattr(dst_fd, name, value, rc, 0);
767                         CT_TRACE("fsetxattr of '%s' on '%s' rc=%d (%s)",
768                                  name, dst, rc, strerror(errno));
769                         /* lustre.* attrs aren't supported on other FS's */
770                         if (rc < 0 && errno != EOPNOTSUPP) {
771                                 rc = -errno;
772                                 CT_ERROR(rc, "cannot set extended attribute"
773                                          " '%s' of '%s'",
774                                          name, dst);
775                                 return rc;
776                         }
777                 }
778                 name += strlen(name) + 1;
779         }
780
781         return 0;
782 }
783
784 static int ct_path_lustre(char *buf, int sz, const char *mnt,
785                           const lustre_fid *fid)
786 {
787         return snprintf(buf, sz, "%s/%s/fid/"DFID_NOBRACE, mnt,
788                         dot_lustre_name, PFID(fid));
789 }
790
791 static int ct_path_archive(char *buf, int sz, const char *archive_dir,
792                            const lustre_fid *fid)
793 {
794         return snprintf(buf, sz, "%s/%04x/%04x/%04x/%04x/%04x/%04x/"
795                         DFID_NOBRACE, archive_dir,
796                         (fid)->f_oid       & 0xFFFF,
797                         (fid)->f_oid >> 16 & 0xFFFF,
798                         (unsigned int)((fid)->f_seq       & 0xFFFF),
799                         (unsigned int)((fid)->f_seq >> 16 & 0xFFFF),
800                         (unsigned int)((fid)->f_seq >> 32 & 0xFFFF),
801                         (unsigned int)((fid)->f_seq >> 48 & 0xFFFF),
802                         PFID(fid));
803 }
804
805 static bool ct_is_retryable(int err)
806 {
807         return err == -ETIMEDOUT;
808 }
809
810 static int ct_begin_restore(struct hsm_copyaction_private **phcp,
811                             const struct hsm_action_item *hai,
812                             int mdt_index, int open_flags)
813 {
814         char     src[PATH_MAX];
815         int      rc;
816
817         rc = llapi_hsm_action_begin(phcp, ctdata, hai, mdt_index, open_flags,
818                                     false);
819         if (rc < 0) {
820                 ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_fid);
821                 CT_ERROR(rc, "llapi_hsm_action_begin() on '%s' failed", src);
822         }
823
824         return rc;
825 }
826
827 static int ct_begin(struct hsm_copyaction_private **phcp,
828                     const struct hsm_action_item *hai)
829 {
830         /* Restore takes specific parameters. Call the same function w/ default
831          * values for all other operations. */
832         return ct_begin_restore(phcp, hai, -1, 0);
833 }
834
835 static int ct_fini(struct hsm_copyaction_private **phcp,
836                    const struct hsm_action_item *hai, int hp_flags, int ct_rc)
837 {
838         struct hsm_copyaction_private   *hcp;
839         char                             lstr[PATH_MAX];
840         int                              rc;
841
842         CT_TRACE("Action completed, notifying coordinator "
843                  "cookie="LPX64", FID="DFID", hp_flags=%d err=%d",
844                  hai->hai_cookie, PFID(&hai->hai_fid),
845                  hp_flags, -ct_rc);
846
847         ct_path_lustre(lstr, sizeof(lstr), opt.o_mnt, &hai->hai_fid);
848
849         if (phcp == NULL || *phcp == NULL) {
850                 rc = llapi_hsm_action_begin(&hcp, ctdata, hai, -1, 0, true);
851                 if (rc < 0) {
852                         CT_ERROR(rc, "llapi_hsm_action_begin() on '%s' failed",
853                                  lstr);
854                         return rc;
855                 }
856                 phcp = &hcp;
857         }
858
859         rc = llapi_hsm_action_end(phcp, &hai->hai_extent, hp_flags, abs(ct_rc));
860         if (rc == -ECANCELED)
861                 CT_ERROR(rc, "completed action on '%s' has been canceled: "
862                          "cookie="LPX64", FID="DFID, lstr, hai->hai_cookie,
863                          PFID(&hai->hai_fid));
864         else if (rc < 0)
865                 CT_ERROR(rc, "llapi_hsm_action_end() on '%s' failed", lstr);
866         else
867                 CT_TRACE("llapi_hsm_action_end() on '%s' ok (rc=%d)",
868                          lstr, rc);
869
870         return rc;
871 }
872
873 static int ct_archive(const struct hsm_action_item *hai, const long hal_flags)
874 {
875         struct hsm_copyaction_private   *hcp = NULL;
876         char                             src[PATH_MAX];
877         char                             dst[PATH_MAX] = "";
878         int                              rc;
879         int                              rcf = 0;
880         bool                             rename_needed = false;
881         int                              hp_flags = 0;
882         int                              open_flags;
883         int                              src_fd = -1;
884         int                              dst_fd = -1;
885
886         rc = ct_begin(&hcp, hai);
887         if (rc < 0)
888                 goto fini_major;
889
890         /* we fill archive so:
891          * source = data FID
892          * destination = lustre FID
893          */
894         ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_dfid);
895         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
896         if (hai->hai_extent.length == -1) {
897                 /* whole file, write it to tmp location and atomically
898                  * replace old archived file */
899                 strlcat(dst, "_tmp", sizeof(dst));
900                 /* we cannot rely on the same test because ct_copy_data()
901                  * updates hai_extent.length */
902                 rename_needed = true;
903         }
904
905         CT_TRACE("archiving '%s' to '%s'", src, dst);
906
907         if (opt.o_dry_run) {
908                 rc = 0;
909                 goto fini_major;
910         }
911
912         rc = ct_mkdir_p(dst);
913         if (rc < 0) {
914                 CT_ERROR(rc, "mkdir_p '%s' failed", dst);
915                 goto fini_major;
916         }
917
918         src_fd = llapi_hsm_action_get_fd(hcp);
919         if (src_fd < 0) {
920                 rc = src_fd;
921                 CT_ERROR(rc, "cannot open '%s' for read", src);
922                 goto fini_major;
923         }
924
925         open_flags = O_WRONLY | O_NOFOLLOW;
926         /* If extent is specified, don't truncate an old archived copy */
927         open_flags |= ((hai->hai_extent.length == -1) ? O_TRUNC : 0) | O_CREAT;
928
929         dst_fd = open(dst, open_flags, FILE_PERM);
930         if (dst_fd == -1) {
931                 rc = -errno;
932                 CT_ERROR(rc, "cannot open '%s' for write", dst);
933                 goto fini_major;
934         }
935
936         /* saving stripe is not critical */
937         rc = ct_save_stripe(src_fd, src, dst);
938         if (rc < 0)
939                 CT_ERROR(rc, "cannot save file striping info of '%s' in '%s'",
940                          src, dst);
941
942         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
943         if (rc < 0) {
944                 CT_ERROR(rc, "data copy failed from '%s' to '%s'", src, dst);
945                 goto fini_major;
946         }
947
948         rc = fsync(dst_fd);
949         if (rc < 0) {
950                 rc = -errno;
951                 CT_ERROR(rc, "cannot flush '%s' archive file '%s'", src, dst);
952                 goto fini_major;
953         }
954
955         CT_TRACE("data archiving for '%s' to '%s' done", src, dst);
956
957         /* attrs will remain on the MDS; no need to copy them, except possibly
958           for disaster recovery */
959         if (opt.o_copy_attrs) {
960                 rc = ct_copy_attr(src, dst, src_fd, dst_fd);
961                 if (rc < 0) {
962                         CT_ERROR(rc, "cannot copy attr of '%s' to '%s'",
963                                  src, dst);
964                         rcf = rc;
965                 }
966                 CT_TRACE("attr file for '%s' saved to archive '%s'",
967                          src, dst);
968         }
969
970         /* xattrs will remain on the MDS; no need to copy them, except possibly
971          for disaster recovery */
972         if (opt.o_copy_xattrs) {
973                 rc = ct_copy_xattr(src, dst, src_fd, dst_fd, false);
974                 if (rc < 0) {
975                         CT_ERROR(rc, "cannot copy xattr of '%s' to '%s'",
976                                  src, dst);
977                         rcf = rcf ? rcf : rc;
978                 }
979                 CT_TRACE("xattr file for '%s' saved to archive '%s'",
980                          src, dst);
981         }
982
983         if (rename_needed == true) {
984                 char     tmp_src[PATH_MAX];
985                 char     tmp_dst[PATH_MAX];
986
987                 /* atomically replace old archived file */
988                 ct_path_archive(src, sizeof(src), opt.o_hsm_root,
989                                 &hai->hai_fid);
990                 rc = rename(dst, src);
991                 if (rc < 0) {
992                         rc = -errno;
993                         CT_ERROR(rc, "cannot rename '%s' to '%s'", dst, src);
994                         goto fini_major;
995                 }
996                 /* rename lov file */
997                 snprintf(tmp_src, sizeof(tmp_src), "%s.lov", src);
998                 snprintf(tmp_dst, sizeof(tmp_dst), "%s.lov", dst);
999                 rc = rename(tmp_dst, tmp_src);
1000                 if (rc < 0)
1001                         CT_ERROR(errno, "cannot rename '%s' to '%s'",
1002                                  tmp_dst, tmp_src);
1003         }
1004
1005         if (opt.o_shadow_tree) {
1006                 /* Create a namespace of softlinks that shadows the original
1007                  * Lustre namespace.  This will only be current at
1008                  * time-of-archive (won't follow renames).
1009                  * WARNING: release won't kill these links; a manual
1010                  * cleanup of dead links would be required.
1011                  */
1012                 char             buf[PATH_MAX];
1013                 long long        recno = -1;
1014                 int              linkno = 0;
1015                 char            *ptr;
1016                 int              depth = 0;
1017                 ssize_t          sz;
1018
1019                 sprintf(buf, DFID, PFID(&hai->hai_fid));
1020                 sprintf(src, "%s/shadow/", opt.o_hsm_root);
1021
1022                 ptr = opt.o_hsm_root;
1023                 while (*ptr)
1024                         (*ptr++ == '/') ? depth-- : 0;
1025
1026                 rc = llapi_fid2path(opt.o_mnt, buf, src + strlen(src),
1027                                     sizeof(src) - strlen(src), &recno, &linkno);
1028                 if (rc < 0) {
1029                         CT_ERROR(rc, "cannot get FID of '%s'", buf);
1030                         rcf = rcf ? rcf : rc;
1031                         goto fini_minor;
1032                 }
1033
1034                 /* Figure out how many parent dirs to symlink back */
1035                 ptr = src;
1036                 while (*ptr)
1037                         (*ptr++ == '/') ? depth++ : 0;
1038                 sprintf(buf, "..");
1039                 while (--depth > 1)
1040                         strcat(buf, "/..");
1041
1042                 ct_path_archive(dst, sizeof(dst), buf, &hai->hai_fid);
1043
1044                 if (ct_mkdir_p(src)) {
1045                         CT_ERROR(errno, "mkdir_p '%s' failed", src);
1046                         rcf = rcf ? rcf : -errno;
1047                         goto fini_minor;
1048                 }
1049                 /* symlink already exists ? */
1050                 sz = readlink(src, buf, sizeof(buf));
1051                 /* detect truncation */
1052                 if (sz == sizeof(buf)) {
1053                         rcf = rcf ? rcf : -E2BIG;
1054                         CT_ERROR(rcf, "readlink '%s' truncated", src);
1055                         goto fini_minor;
1056                 }
1057                 if (sz >= 0) {
1058                         buf[sz] = '\0';
1059                         if (sz == 0 || strncmp(buf, dst, sz) != 0) {
1060                                 if (unlink(src) && errno != ENOENT) {
1061                                         CT_ERROR(errno,
1062                                                  "cannot unlink symlink '%s'",
1063                                                  src);
1064                                         rcf = rcf ? rcf : -errno;
1065                                         goto fini_minor;
1066                                 /* unlink old symlink done */
1067                                 CT_TRACE("remove old symlink '%s' pointing"
1068                                          " to '%s'", src, buf);
1069                                 }
1070                         } else {
1071                                 /* symlink already ok */
1072                                 CT_TRACE("symlink '%s' already pointing"
1073                                          " to '%s'", src, dst);
1074                                 rcf = 0;
1075                                 goto fini_minor;
1076                         }
1077                 }
1078                 if (symlink(dst, src)) {
1079                         CT_ERROR(errno, "cannot symlink '%s' to '%s'",
1080                                  src, dst);
1081                         rcf = rcf ? rcf : -errno;
1082                         goto fini_minor;
1083                 }
1084                 CT_TRACE("symlink '%s' to '%s' done", src, dst);
1085         }
1086 fini_minor:
1087         if (rcf)
1088                 err_minor++;
1089         goto out;
1090
1091
1092 fini_major:
1093         err_major++;
1094
1095         unlink(dst);
1096         if (ct_is_retryable(rc))
1097                 hp_flags |= HP_FLAG_RETRY;
1098
1099         rcf = rc;
1100
1101 out:
1102         if (!(src_fd < 0))
1103                 close(src_fd);
1104
1105         if (!(dst_fd < 0))
1106                 close(dst_fd);
1107
1108         rc = ct_fini(&hcp, hai, hp_flags, rcf);
1109
1110         return rc;
1111 }
1112
1113 static int ct_restore(const struct hsm_action_item *hai, const long hal_flags)
1114 {
1115         struct hsm_copyaction_private   *hcp = NULL;
1116         char                             src[PATH_MAX];
1117         char                             dst[PATH_MAX];
1118         char                             lov_buf[XATTR_SIZE_MAX];
1119         size_t                           lov_size = sizeof(lov_buf);
1120         int                              rc;
1121         int                              hp_flags = 0;
1122         int                              src_fd = -1;
1123         int                              dst_fd = -1;
1124         int                              mdt_index = -1;
1125         int                              open_flags = 0;
1126         bool                             set_lovea;
1127         struct lu_fid                    dfid;
1128         /* we fill lustre so:
1129          * source = lustre FID in the backend
1130          * destination = data FID = volatile file
1131          */
1132
1133         /* build backend file name from released file FID */
1134         ct_path_archive(src, sizeof(src), opt.o_hsm_root, &hai->hai_fid);
1135
1136         rc = llapi_get_mdt_index_by_fid(opt.o_mnt_fd, &hai->hai_fid,
1137                                         &mdt_index);
1138         if (rc < 0) {
1139                 CT_ERROR(rc, "cannot get mdt index "DFID"",
1140                          PFID(&hai->hai_fid));
1141                 return rc;
1142         }
1143         /* restore loads and sets the LOVEA w/o interpreting it to avoid
1144          * dependency on the structure format. */
1145         rc = ct_load_stripe(src, lov_buf, &lov_size);
1146         if (rc < 0) {
1147                 CT_WARN("cannot get stripe rules for '%s' (%s), use default",
1148                         src, strerror(-rc));
1149                 set_lovea = false;
1150         } else {
1151                 open_flags |= O_LOV_DELAY_CREATE;
1152                 set_lovea = true;
1153         }
1154
1155         rc = ct_begin_restore(&hcp, hai, mdt_index, open_flags);
1156         if (rc < 0)
1157                 goto fini;
1158
1159         /* get the FID of the volatile file */
1160         rc = llapi_hsm_action_get_dfid(hcp, &dfid);
1161         if (rc < 0) {
1162                 CT_ERROR(rc, "restoring "DFID
1163                          ", cannot get FID of created volatile file",
1164                          PFID(&hai->hai_fid));
1165                 goto fini;
1166         }
1167
1168         /* build volatile "file name", for messages */
1169         snprintf(dst, sizeof(dst), "{VOLATILE}="DFID, PFID(&dfid));
1170
1171         CT_TRACE("restoring data from '%s' to '%s'", src, dst);
1172
1173         if (opt.o_dry_run) {
1174                 rc = 0;
1175                 goto fini;
1176         }
1177
1178         src_fd = open(src, O_RDONLY | O_NOATIME | O_NOFOLLOW);
1179         if (src_fd < 0) {
1180                 rc = -errno;
1181                 CT_ERROR(rc, "cannot open '%s' for read", src);
1182                 goto fini;
1183         }
1184
1185         dst_fd = llapi_hsm_action_get_fd(hcp);
1186         if (dst_fd < 0) {
1187                 rc = dst_fd;
1188                 CT_ERROR(rc, "cannot open '%s' for write", dst);
1189                 goto fini;
1190         }
1191
1192         if (set_lovea) {
1193                 /* the layout cannot be allocated through .fid so we have to
1194                  * restore a layout */
1195                 rc = ct_restore_stripe(src, dst, dst_fd, lov_buf, lov_size);
1196                 if (rc < 0) {
1197                         CT_ERROR(rc, "cannot restore file striping info"
1198                                  " for '%s' from '%s'", dst, src);
1199                         err_major++;
1200                         goto fini;
1201                 }
1202         }
1203
1204         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
1205         if (rc < 0) {
1206                 CT_ERROR(rc, "cannot copy data from '%s' to '%s'",
1207                          src, dst);
1208                 err_major++;
1209                 if (ct_is_retryable(rc))
1210                         hp_flags |= HP_FLAG_RETRY;
1211                 goto fini;
1212         }
1213
1214         CT_TRACE("data restore from '%s' to '%s' done", src, dst);
1215
1216 fini:
1217         rc = ct_fini(&hcp, hai, hp_flags, rc);
1218
1219         /* object swaping is done by cdt at copy end, so close of volatile file
1220          * cannot be done before */
1221         if (!(src_fd < 0))
1222                 close(src_fd);
1223
1224         if (!(dst_fd < 0))
1225                 close(dst_fd);
1226
1227         return rc;
1228 }
1229
1230 static int ct_remove(const struct hsm_action_item *hai, const long hal_flags)
1231 {
1232         struct hsm_copyaction_private   *hcp = NULL;
1233         char                             dst[PATH_MAX];
1234         int                              rc;
1235
1236         rc = ct_begin(&hcp, hai);
1237         if (rc < 0)
1238                 goto fini;
1239
1240         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
1241
1242         CT_TRACE("removing file '%s'", dst);
1243
1244         if (opt.o_dry_run) {
1245                 rc = 0;
1246                 goto fini;
1247         }
1248
1249         rc = unlink(dst);
1250         if (rc < 0) {
1251                 rc = -errno;
1252                 CT_ERROR(rc, "cannot unlink '%s'", dst);
1253                 err_minor++;
1254                 goto fini;
1255         }
1256
1257         strlcat(dst, ".lov", sizeof(dst));
1258         rc = unlink(dst);
1259         if (rc < 0) {
1260                 rc = -errno;
1261                 CT_ERROR(rc, "cannot unlink '%s'", dst);
1262                 err_minor++;
1263                 goto fini;
1264         }
1265
1266 fini:
1267         rc = ct_fini(&hcp, hai, 0, rc);
1268
1269         return rc;
1270 }
1271
1272 static int ct_process_item(struct hsm_action_item *hai, const long hal_flags)
1273 {
1274         int     rc = 0;
1275
1276         if (opt.o_verbose >= LLAPI_MSG_INFO || opt.o_dry_run) {
1277                 /* Print the original path */
1278                 char            fid[128];
1279                 char            path[PATH_MAX];
1280                 long long       recno = -1;
1281                 int             linkno = 0;
1282
1283                 sprintf(fid, DFID, PFID(&hai->hai_fid));
1284                 CT_TRACE("'%s' action %s reclen %d, cookie="LPX64,
1285                          fid, hsm_copytool_action2name(hai->hai_action),
1286                          hai->hai_len, hai->hai_cookie);
1287                 rc = llapi_fid2path(opt.o_mnt, fid, path,
1288                                     sizeof(path), &recno, &linkno);
1289                 if (rc < 0)
1290                         CT_ERROR(rc, "cannot get path of FID %s", fid);
1291                 else
1292                         CT_TRACE("processing file '%s'", path);
1293         }
1294
1295         switch (hai->hai_action) {
1296         /* set err_major, minor inside these functions */
1297         case HSMA_ARCHIVE:
1298                 rc = ct_archive(hai, hal_flags);
1299                 break;
1300         case HSMA_RESTORE:
1301                 rc = ct_restore(hai, hal_flags);
1302                 break;
1303         case HSMA_REMOVE:
1304                 rc = ct_remove(hai, hal_flags);
1305                 break;
1306         case HSMA_CANCEL:
1307                 CT_TRACE("cancel not implemented for file system '%s'",
1308                          opt.o_mnt);
1309                 /* Don't report progress to coordinator for this cookie:
1310                  * the copy function will get ECANCELED when reporting
1311                  * progress. */
1312                 err_minor++;
1313                 return 0;
1314                 break;
1315         default:
1316                 rc = -EINVAL;
1317                 CT_ERROR(rc, "unknown action %d, on '%s'", hai->hai_action,
1318                          opt.o_mnt);
1319                 err_minor++;
1320                 ct_fini(NULL, hai, 0, rc);
1321         }
1322
1323         return 0;
1324 }
1325
1326 struct ct_th_data {
1327         long                     hal_flags;
1328         struct hsm_action_item  *hai;
1329 };
1330
1331 static void *ct_thread(void *data)
1332 {
1333         struct ct_th_data *cttd = data;
1334         int rc;
1335
1336         rc = ct_process_item(cttd->hai, cttd->hal_flags);
1337
1338         free(cttd->hai);
1339         free(cttd);
1340         pthread_exit((void *)(intptr_t)rc);
1341 }
1342
1343 static int ct_process_item_async(const struct hsm_action_item *hai,
1344                                  long hal_flags)
1345 {
1346         pthread_attr_t           attr;
1347         pthread_t                thread;
1348         struct ct_th_data       *data;
1349         int                      rc;
1350
1351         data = malloc(sizeof(*data));
1352         if (data == NULL)
1353                 return -ENOMEM;
1354
1355         data->hai = malloc(hai->hai_len);
1356         if (data->hai == NULL) {
1357                 free(data);
1358                 return -ENOMEM;
1359         }
1360
1361         memcpy(data->hai, hai, hai->hai_len);
1362         data->hal_flags = hal_flags;
1363
1364         rc = pthread_attr_init(&attr);
1365         if (rc != 0) {
1366                 CT_ERROR(rc, "pthread_attr_init failed for '%s' service",
1367                          opt.o_mnt);
1368                 free(data->hai);
1369                 free(data);
1370                 return -rc;
1371         }
1372
1373         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1374
1375         rc = pthread_create(&thread, &attr, ct_thread, data);
1376         if (rc != 0)
1377                 CT_ERROR(rc, "cannot create thread for '%s' service",
1378                          opt.o_mnt);
1379
1380         pthread_attr_destroy(&attr);
1381         return 0;
1382 }
1383
1384 static int ct_import_one(const char *src, const char *dst)
1385 {
1386         char            newarc[PATH_MAX];
1387         lustre_fid      fid;
1388         struct stat     st;
1389         int             rc;
1390
1391         CT_TRACE("importing '%s' from '%s'", dst, src);
1392
1393         if (stat(src, &st) < 0) {
1394                 rc = -errno;
1395                 CT_ERROR(rc, "cannot stat '%s'", src);
1396                 return rc;
1397         }
1398
1399         if (opt.o_dry_run)
1400                 return 0;
1401
1402         rc = llapi_hsm_import(dst,
1403                               opt.o_archive_cnt ? opt.o_archive_id[0] : 0,
1404                               &st, 0, 0, 0, 0, NULL, &fid);
1405         if (rc < 0) {
1406                 CT_ERROR(rc, "cannot import '%s' from '%s'", dst, src);
1407                 return rc;
1408         }
1409
1410         ct_path_archive(newarc, sizeof(newarc), opt.o_hsm_root, &fid);
1411
1412         rc = ct_mkdir_p(newarc);
1413         if (rc < 0) {
1414                 CT_ERROR(rc, "mkdir_p '%s' failed", newarc);
1415                 err_major++;
1416                 return rc;
1417
1418         }
1419
1420         /* Lots of choices now: mv, ln, ln -s ? */
1421         rc = link(src, newarc); /* hardlink */
1422         if (rc < 0) {
1423                 rc = -errno;
1424                 CT_ERROR(rc, "cannot link '%s' to '%s'", newarc, src);
1425                 err_major++;
1426                 return rc;
1427         }
1428         CT_TRACE("imported '%s' from '%s'=='%s'", dst, newarc, src);
1429
1430         return 0;
1431 }
1432
1433 static char *path_concat(const char *dirname, const char *basename)
1434 {
1435         char    *result;
1436         int      rc;
1437
1438         rc = asprintf(&result, "%s/%s", dirname, basename);
1439         if (rc < 0)
1440                 return NULL;
1441
1442         return result;
1443 }
1444
1445 static int ct_import_fid(const lustre_fid *import_fid)
1446 {
1447         char    fid_path[PATH_MAX];
1448         int     rc;
1449
1450         ct_path_lustre(fid_path, sizeof(fid_path), opt.o_mnt, import_fid);
1451         rc = access(fid_path, F_OK);
1452         if (rc == 0 || errno != ENOENT) {
1453                 rc = (errno == 0) ? -EEXIST : -errno;
1454                 CT_ERROR(rc, "cannot import '"DFID"'", PFID(import_fid));
1455                 return rc;
1456         }
1457
1458         ct_path_archive(fid_path, sizeof(fid_path), opt.o_hsm_root,
1459                         import_fid);
1460
1461         CT_TRACE("Resolving "DFID" to %s", PFID(import_fid), fid_path);
1462
1463         return ct_import_one(fid_path, opt.o_dst);
1464 }
1465
1466 static int ct_import_recurse(const char *relpath)
1467 {
1468         DIR             *dir;
1469         struct dirent    ent, *cookie = NULL;
1470         char            *srcpath, *newpath;
1471         lustre_fid       import_fid;
1472         int              rc;
1473
1474         if (relpath == NULL)
1475                 return -EINVAL;
1476
1477         /* Is relpath a FID? In which case SFID should expand to three
1478          * elements. */
1479         rc = sscanf(relpath, SFID, RFID(&import_fid));
1480         if (rc == 3)
1481                 return ct_import_fid(&import_fid);
1482
1483         srcpath = path_concat(opt.o_hsm_root, relpath);
1484         if (srcpath == NULL) {
1485                 err_major++;
1486                 return -ENOMEM;
1487         }
1488
1489         dir = opendir(srcpath);
1490         if (dir == NULL) {
1491                 /* Not a dir, or error */
1492                 if (errno == ENOTDIR) {
1493                         /* Single regular file case, treat o_dst as absolute
1494                            final location. */
1495                         rc = ct_import_one(srcpath, opt.o_dst);
1496                 } else {
1497                         rc = -errno;
1498                         CT_ERROR(rc, "cannot opendir '%s'", srcpath);
1499                         err_major++;
1500                 }
1501                 free(srcpath);
1502                 return rc;
1503         }
1504         free(srcpath);
1505
1506         while (1) {
1507                 rc = readdir_r(dir, &ent, &cookie);
1508                 if (rc != 0) {
1509                         rc = -errno;
1510                         CT_ERROR(rc, "cannot readdir_r '%s'", relpath);
1511                         err_major++;
1512                         goto out;
1513                 } else if ((rc == 0) && (cookie == NULL)) {
1514                         /* end of directory */
1515                         break;
1516                 }
1517
1518                 if (!strcmp(ent.d_name, ".") ||
1519                     !strcmp(ent.d_name, ".."))
1520                         continue;
1521
1522                 /* New relative path */
1523                 newpath = path_concat(relpath, ent.d_name);
1524                 if (newpath == NULL) {
1525                         err_major++;
1526                         rc = -ENOMEM;
1527                         goto out;
1528                 }
1529
1530                 if (ent.d_type == DT_DIR) {
1531                         rc = ct_import_recurse(newpath);
1532                 } else {
1533                         char src[PATH_MAX];
1534                         char dst[PATH_MAX];
1535
1536                         sprintf(src, "%s/%s", opt.o_hsm_root, newpath);
1537                         sprintf(dst, "%s/%s", opt.o_dst, newpath);
1538                         /* Make the target dir in the Lustre fs */
1539                         rc = ct_mkdir_p(dst);
1540                         if (rc == 0) {
1541                                 /* Import the file */
1542                                 rc = ct_import_one(src, dst);
1543                         } else {
1544                                 CT_ERROR(rc, "ct_mkdir_p '%s' failed", dst);
1545                                 err_major++;
1546                         }
1547                 }
1548
1549                 if (rc != 0) {
1550                         CT_ERROR(rc, "cannot import '%s'", newpath);
1551                         if (err_major && opt.o_abort_on_error) {
1552                                 free(newpath);
1553                                 goto out;
1554                         }
1555                 }
1556                 free(newpath);
1557         }
1558
1559         rc = 0;
1560 out:
1561         closedir(dir);
1562         return rc;
1563 }
1564
1565 static int ct_rebind_one(const lustre_fid *old_fid, const lustre_fid *new_fid)
1566 {
1567         char    src[PATH_MAX];
1568         char    dst[PATH_MAX];
1569         int     rc;
1570
1571         CT_TRACE("rebind "DFID" to "DFID, PFID(old_fid), PFID(new_fid));
1572
1573         ct_path_archive(src, sizeof(src), opt.o_hsm_root, old_fid);
1574         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, new_fid);
1575
1576         if (!opt.o_dry_run) {
1577                 ct_mkdir_p(dst);
1578                 if (rename(src, dst)) {
1579                         rc = -errno;
1580                         CT_ERROR(rc, "cannot rename '%s' to '%s'", src, dst);
1581                         return -errno;
1582                 }
1583                 /* rename lov file */
1584                 strlcat(src, ".lov", sizeof(src));
1585                 strlcat(dst, ".lov", sizeof(dst));
1586                 if (rename(src, dst))
1587                         CT_ERROR(errno, "cannot rename '%s' to '%s'", src, dst);
1588
1589         }
1590         return 0;
1591 }
1592
1593 static bool fid_is_file(lustre_fid *fid)
1594 {
1595         return fid_is_norm(fid) || fid_is_igif(fid);
1596 }
1597
1598 static bool should_ignore_line(const char *line)
1599 {
1600         int     i;
1601
1602         for (i = 0; line[i] != '\0'; i++) {
1603                 if (isspace(line[i]))
1604                         continue;
1605                 else if (line[i] == '#')
1606                         return true;
1607                 else
1608                         return false;
1609         }
1610
1611         return true;
1612 }
1613
1614 static int ct_rebind_list(const char *list)
1615 {
1616         int              rc;
1617         FILE            *filp;
1618         ssize_t          r;
1619         char            *line = NULL;
1620         size_t           line_size = 0;
1621         unsigned int     nl = 0;
1622         unsigned int     ok = 0;
1623
1624         filp = fopen(list, "r");
1625         if (filp == NULL) {
1626                 rc = -errno;
1627                 CT_ERROR(rc, "cannot open '%s'", list);
1628                 return rc;
1629         }
1630
1631         /* each line consists of 2 FID */
1632         while ((r = getline(&line, &line_size, filp)) != -1) {
1633                 lustre_fid      old_fid;
1634                 lustre_fid      new_fid;
1635
1636                 /* Ignore empty and commented out ('#...') lines. */
1637                 if (should_ignore_line(line))
1638                         continue;
1639
1640                 nl++;
1641
1642                 rc = sscanf(line, SFID" "SFID, RFID(&old_fid), RFID(&new_fid));
1643                 if (rc != 6 || !fid_is_file(&old_fid) ||
1644                     !fid_is_file(&new_fid)) {
1645                         CT_ERROR(EINVAL,
1646                                  "'%s' FID expected near '%s', line %u",
1647                                  list, line, nl);
1648                         err_major++;
1649                         continue;
1650                 }
1651
1652                 if (ct_rebind_one(&old_fid, &new_fid))
1653                         err_major++;
1654                 else
1655                         ok++;
1656         }
1657
1658         fclose(filp);
1659
1660         if (line)
1661                 free(line);
1662
1663         /* return 0 if all rebinds were successful */
1664         CT_TRACE("%u lines read from '%s', %u rebind successful", nl, list, ok);
1665
1666         return ok == nl ? 0 : -1;
1667 }
1668
1669 static int ct_rebind(void)
1670 {
1671         int     rc;
1672
1673         if (opt.o_dst) {
1674                 lustre_fid      old_fid;
1675                 lustre_fid      new_fid;
1676
1677                 if (sscanf(opt.o_src, SFID, RFID(&old_fid)) != 3 ||
1678                     !fid_is_file(&old_fid)) {
1679                         rc = -EINVAL;
1680                         CT_ERROR(rc, "'%s' invalid FID format", opt.o_src);
1681                         return rc;
1682                 }
1683
1684                 if (sscanf(opt.o_dst, SFID, RFID(&new_fid)) != 3 ||
1685                     !fid_is_file(&new_fid)) {
1686                         rc = -EINVAL;
1687                         CT_ERROR(rc, "'%s' invalid FID format", opt.o_dst);
1688                         return rc;
1689                 }
1690
1691                 rc = ct_rebind_one(&old_fid, &new_fid);
1692
1693                 return rc;
1694         }
1695
1696         /* o_src is a list file */
1697         rc = ct_rebind_list(opt.o_src);
1698
1699         return rc;
1700 }
1701
1702 static int ct_dir_level_max(const char *dirpath, __u16 *sub_seqmax)
1703 {
1704         DIR             *dir;
1705         int              rc;
1706         __u16            sub_seq;
1707         struct dirent    ent, *cookie = NULL;
1708
1709         *sub_seqmax = 0;
1710
1711         dir = opendir(dirpath);
1712         if (dir == NULL) {
1713                 rc = -errno;
1714                 CT_ERROR(rc, "cannot open directory '%s'", opt.o_hsm_root);
1715                 return rc;
1716         }
1717
1718         while ((rc = readdir_r(dir, &ent, &cookie)) == 0) {
1719                 if (cookie == NULL)
1720                         /* end of directory.
1721                          * rc is 0 and seqmax contains the max value. */
1722                         goto out;
1723
1724                 if (!strcmp(ent.d_name, ".") || !strcmp(ent.d_name, ".."))
1725                         continue;
1726
1727                 if (sscanf(ent.d_name, "%hx", &sub_seq) != 1) {
1728                         CT_TRACE("'%s' has an unexpected dirname format, "
1729                                  "skip entry", ent.d_name);
1730                         continue;
1731                 }
1732                 if (sub_seq > *sub_seqmax)
1733                         *sub_seqmax = sub_seq;
1734         }
1735         rc = -errno;
1736         CT_ERROR(rc, "cannot readdir_r '%s'", dirpath);
1737
1738 out:
1739         closedir(dir);
1740         return rc;
1741 }
1742
1743 static int ct_max_sequence(void)
1744 {
1745         int     rc, i;
1746         char    path[PATH_MAX];
1747         __u64   seq = 0;
1748         __u16   subseq;
1749
1750         strlcpy(path, opt.o_hsm_root, sizeof(path));
1751         /* FID sequence is stored in top-level directory names:
1752          * hsm_root/16bits (high weight)/16 bits/16 bits/16 bits (low weight).
1753          */
1754         for (i = 0; i < 4; i++) {
1755                 size_t path_len;
1756
1757                 rc = ct_dir_level_max(path, &subseq);
1758                 if (rc != 0)
1759                         return rc;
1760                 seq |= ((__u64)subseq << ((3 - i) * 16));
1761                 path_len = strlen(path);
1762                 rc = snprintf(path + path_len, sizeof(path) - path_len,
1763                               "/%04x", subseq);
1764                 if (rc >= (sizeof(path) - path_len))
1765                         return -E2BIG;
1766                 path[sizeof(path) - 1] = '\0';
1767         }
1768
1769         printf("max_sequence: "LPX64"\n", seq);
1770
1771         return 0;
1772 }
1773
1774 static void handler(int signal)
1775 {
1776         psignal(signal, "exiting");
1777         /* If we don't clean up upon interrupt, umount thinks there's a ref
1778          * and doesn't remove us from mtab (EINPROGRESS). The lustre client
1779          * does successfully unmount and the mount is actually gone, but the
1780          * mtab entry remains. So this just makes mtab happier. */
1781         llapi_hsm_copytool_unregister(&ctdata);
1782
1783         /* Also remove fifo upon signal as during normal/error exit */
1784         if (opt.o_event_fifo != NULL)
1785                 llapi_hsm_unregister_event_fifo(opt.o_event_fifo);
1786         _exit(1);
1787 }
1788
1789 /* Daemon waits for messages from the kernel; run it in the background. */
1790 static int ct_run(void)
1791 {
1792         int     rc;
1793
1794         if (opt.o_daemonize) {
1795                 rc = daemon(1, 1);
1796                 if (rc < 0) {
1797                         rc = -errno;
1798                         CT_ERROR(rc, "cannot daemonize");
1799                         return rc;
1800                 }
1801         }
1802
1803         setbuf(stdout, NULL);
1804
1805         if (opt.o_event_fifo != NULL) {
1806                 rc = llapi_hsm_register_event_fifo(opt.o_event_fifo);
1807                 if (rc < 0) {
1808                         CT_ERROR(rc, "failed to register event fifo");
1809                         return rc;
1810                 }
1811                 llapi_error_callback_set(llapi_hsm_log_error);
1812         }
1813
1814         rc = llapi_hsm_copytool_register(&ctdata, opt.o_mnt,
1815                                          opt.o_archive_cnt,
1816                                          opt.o_archive_id, 0);
1817         if (rc < 0) {
1818                 CT_ERROR(rc, "cannot start copytool interface");
1819                 return rc;
1820         }
1821
1822         signal(SIGINT, handler);
1823         signal(SIGTERM, handler);
1824
1825         while (1) {
1826                 struct hsm_action_list  *hal;
1827                 struct hsm_action_item  *hai;
1828                 int                      msgsize;
1829                 int                      i = 0;
1830
1831                 CT_TRACE("waiting for message from kernel");
1832
1833                 rc = llapi_hsm_copytool_recv(ctdata, &hal, &msgsize);
1834                 if (rc == -ESHUTDOWN) {
1835                         CT_TRACE("shutting down");
1836                         break;
1837                 } else if (rc < 0) {
1838                         CT_WARN("cannot receive action list: %s",
1839                                 strerror(-rc));
1840                         err_major++;
1841                         if (opt.o_abort_on_error)
1842                                 break;
1843                         else
1844                                 continue;
1845                 }
1846
1847                 CT_TRACE("copytool fs=%s archive#=%d item_count=%d",
1848                          hal->hal_fsname, hal->hal_archive_id, hal->hal_count);
1849
1850                 if (strcmp(hal->hal_fsname, fs_name) != 0) {
1851                         rc = -EINVAL;
1852                         CT_ERROR(rc, "'%s' invalid fs name, expecting: %s",
1853                                  hal->hal_fsname, fs_name);
1854                         err_major++;
1855                         if (opt.o_abort_on_error)
1856                                 break;
1857                         else
1858                                 continue;
1859                 }
1860
1861                 hai = hai_first(hal);
1862                 while (++i <= hal->hal_count) {
1863                         if ((char *)hai - (char *)hal > msgsize) {
1864                                 rc = -EPROTO;
1865                                 CT_ERROR(rc,
1866                                          "'%s' item %d past end of message!",
1867                                          opt.o_mnt, i);
1868                                 err_major++;
1869                                 break;
1870                         }
1871                         rc = ct_process_item_async(hai, hal->hal_flags);
1872                         if (rc < 0)
1873                                 CT_ERROR(rc, "'%s' item %d process",
1874                                          opt.o_mnt, i);
1875                         if (opt.o_abort_on_error && err_major)
1876                                 break;
1877                         hai = hai_next(hai);
1878                 }
1879
1880                 if (opt.o_abort_on_error && err_major)
1881                         break;
1882         }
1883
1884         llapi_hsm_copytool_unregister(&ctdata);
1885         if (opt.o_event_fifo != NULL)
1886                 llapi_hsm_unregister_event_fifo(opt.o_event_fifo);
1887
1888         return rc;
1889 }
1890
1891 static int ct_setup(void)
1892 {
1893         int     rc;
1894
1895         /* set llapi message level */
1896         llapi_msg_set_level(opt.o_verbose);
1897
1898         arc_fd = open(opt.o_hsm_root, O_RDONLY);
1899         if (arc_fd < 0) {
1900                 rc = -errno;
1901                 CT_ERROR(rc, "cannot open archive at '%s'", opt.o_hsm_root);
1902                 return rc;
1903         }
1904
1905         rc = llapi_search_fsname(opt.o_mnt, fs_name);
1906         if (rc < 0) {
1907                 CT_ERROR(rc, "cannot find a Lustre filesystem mounted at '%s'",
1908                          opt.o_mnt);
1909                 return rc;
1910         }
1911
1912         opt.o_mnt_fd = open(opt.o_mnt, O_RDONLY);
1913         if (opt.o_mnt_fd < 0) {
1914                 rc = -errno;
1915                 CT_ERROR(rc, "cannot open mount point at '%s'",
1916                          opt.o_mnt);
1917                 return rc;
1918         }
1919
1920         return rc;
1921 }
1922
1923 static int ct_cleanup(void)
1924 {
1925         int     rc;
1926
1927         if (opt.o_mnt_fd >= 0) {
1928                 rc = close(opt.o_mnt_fd);
1929                 if (rc < 0) {
1930                         rc = -errno;
1931                         CT_ERROR(rc, "cannot close mount point");
1932                         return rc;
1933                 }
1934         }
1935
1936         if (arc_fd >= 0) {
1937                 rc = close(arc_fd);
1938                 if (rc < 0) {
1939                         rc = -errno;
1940                         CT_ERROR(rc, "cannot close archive root directory");
1941                         return rc;
1942                 }
1943         }
1944
1945         return 0;
1946 }
1947
1948 int main(int argc, char **argv)
1949 {
1950         int     rc;
1951
1952         strlcpy(cmd_name, basename(argv[0]), sizeof(cmd_name));
1953         rc = ct_parseopts(argc, argv);
1954         if (rc < 0) {
1955                 CT_WARN("try '%s --help' for more information", cmd_name);
1956                 return -rc;
1957         }
1958
1959         rc = ct_setup();
1960         if (rc < 0)
1961                 goto error_cleanup;
1962
1963         switch (opt.o_action) {
1964         case CA_IMPORT:
1965                 rc = ct_import_recurse(opt.o_src);
1966                 break;
1967         case CA_REBIND:
1968                 rc = ct_rebind();
1969                 break;
1970         case CA_MAXSEQ:
1971                 rc = ct_max_sequence();
1972                 break;
1973         default:
1974                 rc = ct_run();
1975                 break;
1976         }
1977
1978         if (opt.o_action != CA_MAXSEQ)
1979                 CT_TRACE("process finished, errs: %d major, %d minor,"
1980                          " rc=%d (%s)", err_major, err_minor, rc,
1981                          strerror(-rc));
1982
1983 error_cleanup:
1984         ct_cleanup();
1985
1986         return -rc;
1987 }
1988