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