Whamcloud - gitweb
LU-7635 utils: Fix lhsmtool_posix interval reporting
[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 <stdio.h>
41 #include <stdint.h>
42 #include <stdlib.h>
43 #include <dirent.h>
44 #include <errno.h>
45 #include <getopt.h>
46 #include <pthread.h>
47 #include <time.h>
48 #include <unistd.h>
49 #include <utime.h>
50 #include <sys/time.h>
51 #include <sys/xattr.h>
52 #include <sys/syscall.h>
53 #include <sys/types.h>
54 #include <libcfs/util/string.h>
55 #include <lustre/lustre_idl.h>
56 #include <lustre/lustreapi.h>
57
58 /* Progress reporting period */
59 #define REPORT_INTERVAL_DEFAULT 30
60 /* HSM hash subdir permissions */
61 #define DIR_PERM S_IRWXU
62 /* HSM hash file permissions */
63 #define FILE_PERM (S_IRUSR | S_IWUSR)
64
65 #define ONE_MB 0x100000
66
67 #ifndef NSEC_PER_SEC
68 # define NSEC_PER_SEC 1000000000UL
69 #endif
70
71 enum ct_action {
72         CA_IMPORT = 1,
73         CA_REBIND,
74         CA_MAXSEQ,
75 };
76
77 struct options {
78         int                      o_copy_attrs;
79         int                      o_daemonize;
80         int                      o_dry_run;
81         int                      o_abort_on_error;
82         int                      o_shadow_tree;
83         int                      o_verbose;
84         int                      o_copy_xattrs;
85         int                      o_archive_cnt;
86         int                      o_archive_id[LL_HSM_MAX_ARCHIVE];
87         int                      o_report_int;
88         unsigned long long       o_bandwidth;
89         size_t                   o_chunk_size;
90         enum ct_action           o_action;
91         char                    *o_event_fifo;
92         char                    *o_mnt;
93         int                      o_mnt_fd;
94         char                    *o_hsm_root;
95         char                    *o_src; /* for import, or rebind */
96         char                    *o_dst; /* for import, or rebind */
97 };
98
99 /* everything else is zeroed */
100 struct options opt = {
101         .o_copy_attrs = 1,
102         .o_shadow_tree = 1,
103         .o_verbose = LLAPI_MSG_INFO,
104         .o_copy_xattrs = 1,
105         .o_report_int = REPORT_INTERVAL_DEFAULT,
106         .o_chunk_size = ONE_MB,
107 };
108
109 /* hsm_copytool_private will hold an open FD on the lustre mount point
110  * for us. Additionally open one on the archive FS root to make sure
111  * it doesn't drop out from under us (and remind the admin to shutdown
112  * the copytool before unmounting). */
113
114 static int arc_fd = -1;
115
116 static int err_major;
117 static int err_minor;
118
119 static char cmd_name[PATH_MAX];
120 static char fs_name[MAX_OBD_NAME + 1];
121
122 static struct hsm_copytool_private *ctdata;
123
124 static inline double ct_now(void)
125 {
126         struct timeval tv;
127
128         gettimeofday(&tv, NULL);
129
130         return tv.tv_sec + 0.000001 * tv.tv_usec;
131 }
132
133 #define CT_ERROR(_rc, _format, ...)                                     \
134         llapi_error(LLAPI_MSG_ERROR, _rc,                               \
135                     "%f %s[%ld]: "_format,                              \
136                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
137
138 #define CT_DEBUG(_format, ...)                                          \
139         llapi_error(LLAPI_MSG_DEBUG | LLAPI_MSG_NO_ERRNO, 0,            \
140                     "%f %s[%ld]: "_format,                              \
141                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
142
143 #define CT_WARN(_format, ...) \
144         llapi_error(LLAPI_MSG_WARN | LLAPI_MSG_NO_ERRNO, 0,             \
145                     "%f %s[%ld]: "_format,                              \
146                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
147
148 #define CT_TRACE(_format, ...)                                          \
149         llapi_error(LLAPI_MSG_INFO | LLAPI_MSG_NO_ERRNO, 0,             \
150                     "%f %s[%ld]: "_format,                              \
151                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
152
153 static void usage(const char *name, int rc)
154 {
155         fprintf(stdout,
156         " Usage: %s [options]... <mode> <lustre_mount_point>\n"
157         "The Lustre HSM Posix copy tool can be used as a daemon or "
158         "as a command line tool\n"
159         "The Lustre HSM daemon acts on action requests from Lustre\n"
160         "to copy files to and from an HSM archive system.\n"
161         "This POSIX-flavored daemon makes regular POSIX filesystem calls\n"
162         "to an HSM mounted at a given hsm_root.\n"
163         "   --daemon            Daemon mode, run in background\n"
164         " Options:\n"
165         "   --no-attr           Don't copy file attributes\n"
166         "   --no-shadow         Don't create shadow namespace in archive\n"
167         "   --no-xattr          Don't copy file extended attributes\n"
168         "The Lustre HSM tool performs administrator-type actions\n"
169         "on a Lustre HSM archive.\n"
170         "This POSIX-flavored tool can link an existing HSM namespace\n"
171         "into a Lustre filesystem.\n"
172         " Usage:\n"
173         "   %s [options] --import <src> <dst> <lustre_mount_point>\n"
174         "      import an archived subtree from\n"
175         "       <src> (FID or relative path to hsm_root) into the Lustre\n"
176         "             filesystem at\n"
177         "       <dst> (absolute path)\n"
178         "   %s [options] --rebind <old_FID> <new_FID> <lustre_mount_point>\n"
179         "      rebind an entry in the HSM to a new FID\n"
180         "       <old_FID> old FID the HSM entry is bound to\n"
181         "       <new_FID> new FID to bind the HSM entry to\n"
182         "   %s [options] --rebind <list_file> <lustre_mount_point>\n"
183         "      perform the rebind operation for all FID in the list file\n"
184         "       each line of <list_file> consists of <old_FID> <new_FID>\n"
185         "   %s [options] --max-sequence <fsname>\n"
186         "       return the max fid sequence of archived files\n"
187         "   --abort-on-error          Abort operation on major error\n"
188         "   -A, --archive <#>         Archive number (repeatable)\n"
189         "   -b, --bandwidth <bw>      Limit I/O bandwidth (unit can be used\n,"
190         "                             default is MB)\n"
191         "   --dry-run                 Don't run, just show what would be done\n"
192         "   -c, --chunk-size <sz>     I/O size used during data copy\n"
193         "                             (unit can be used, default is MB)\n"
194         "   -f, --event-fifo <path>   Write events stream to fifo\n"
195         "   -p, --hsm-root <path>     Target HSM mount point\n"
196         "   -q, --quiet               Produce less verbose output\n"
197         "   -u, --update-interval <s> Interval between progress reports sent\n"
198         "                             to Coordinator\n"
199         "   -v, --verbose             Produce more verbose output\n",
200         cmd_name, cmd_name, cmd_name, cmd_name, cmd_name);
201
202         exit(rc);
203 }
204
205 static int ct_parseopts(int argc, char * const *argv)
206 {
207         struct option long_opts[] = {
208                 {"abort-on-error", no_argument,       &opt.o_abort_on_error, 1},
209                 {"abort_on_error", no_argument,       &opt.o_abort_on_error, 1},
210                 {"archive",        required_argument, NULL,                'A'},
211                 {"bandwidth",      required_argument, NULL,                'b'},
212                 {"chunk-size",     required_argument, NULL,                'c'},
213                 {"chunk_size",     required_argument, NULL,                'c'},
214                 {"daemon",         no_argument,       &opt.o_daemonize,     1},
215                 {"event-fifo",     required_argument, NULL,                'f'},
216                 {"event_fifo",     required_argument, NULL,                'f'},
217                 {"dry-run",        no_argument,       &opt.o_dry_run,       1},
218                 {"help",           no_argument,       NULL,                'h'},
219                 {"hsm-root",       required_argument, NULL,                'p'},
220                 {"hsm_root",       required_argument, NULL,                'p'},
221                 {"import",         no_argument,       NULL,                'i'},
222                 {"max-sequence",   no_argument,       NULL,                'M'},
223                 {"max_sequence",   no_argument,       NULL,                'M'},
224                 {"no-attr",        no_argument,       &opt.o_copy_attrs,    0},
225                 {"no_attr",        no_argument,       &opt.o_copy_attrs,    0},
226                 {"no-shadow",      no_argument,       &opt.o_shadow_tree,   0},
227                 {"no_shadow",      no_argument,       &opt.o_shadow_tree,   0},
228                 {"no-xattr",       no_argument,       &opt.o_copy_xattrs,   0},
229                 {"no_xattr",       no_argument,       &opt.o_copy_xattrs,   0},
230                 {"quiet",          no_argument,       NULL,                'q'},
231                 {"rebind",         no_argument,       NULL,                'r'},
232                 {"update-interval", required_argument,  NULL,              'u'},
233                 {"update_interval", required_argument,  NULL,              'u'},
234                 {"verbose",        no_argument,       NULL,                'v'},
235                 {0, 0, 0, 0}
236         };
237         int                      c, rc;
238         unsigned long long       value;
239         unsigned long long       unit;
240
241         optind = 0;
242         while ((c = getopt_long(argc, argv, "A:b:c:f:hiMp:qru:v",
243                                 long_opts, NULL)) != -1) {
244                 switch (c) {
245                 case 'A':
246                         if ((opt.o_archive_cnt >= LL_HSM_MAX_ARCHIVE) ||
247                             (atoi(optarg) >= LL_HSM_MAX_ARCHIVE)) {
248                                 rc = -E2BIG;
249                                 CT_ERROR(rc, "archive number must be less"
250                                          "than %zu", LL_HSM_MAX_ARCHIVE);
251                                 return rc;
252                         }
253                         opt.o_archive_id[opt.o_archive_cnt] = atoi(optarg);
254                         opt.o_archive_cnt++;
255                         break;
256                 case 'b': /* -b and -c have both a number with unit as arg */
257                 case 'c':
258                         unit = ONE_MB;
259                         if (llapi_parse_size(optarg, &value, &unit, 0) < 0) {
260                                 rc = -EINVAL;
261                                 CT_ERROR(rc, "bad value for -%c '%s'", c,
262                                          optarg);
263                                 return rc;
264                         }
265                         if (c == 'c')
266                                 opt.o_chunk_size = value;
267                         else
268                                 opt.o_bandwidth = value;
269                         break;
270                 case 'f':
271                         opt.o_event_fifo = optarg;
272                         break;
273                 case 'h':
274                         usage(argv[0], 0);
275                 case 'i':
276                         opt.o_action = CA_IMPORT;
277                         break;
278                 case 'M':
279                         opt.o_action = CA_MAXSEQ;
280                         break;
281                 case 'p':
282                         opt.o_hsm_root = optarg;
283                         break;
284                 case 'q':
285                         opt.o_verbose--;
286                         break;
287                 case 'r':
288                         opt.o_action = CA_REBIND;
289                         break;
290                 case 'u':
291                         opt.o_report_int = atoi(optarg);
292                         if (opt.o_report_int < 0) {
293                                 rc = -EINVAL;
294                                 CT_ERROR(rc, "bad value for -%c '%s'", c,
295                                          optarg);
296                                 return rc;
297                         }
298                         break;
299                 case 'v':
300                         opt.o_verbose++;
301                         break;
302                 case 0:
303                         break;
304                 default:
305                         return -EINVAL;
306                 }
307         }
308
309         switch (opt.o_action) {
310         case CA_IMPORT:
311                 /* src dst mount_point */
312                 if (argc != optind + 3) {
313                         rc = -EINVAL;
314                         CT_ERROR(rc, "--import requires 2 arguments");
315                         return rc;
316                 }
317                 opt.o_src = argv[optind++];
318                 opt.o_dst = argv[optind++];
319                 break;
320         case CA_REBIND:
321                 /* FID1 FID2 mount_point or FILE mount_point */
322                 if (argc == optind + 2) {
323                         opt.o_src = argv[optind++];
324                         opt.o_dst = NULL;
325                 } else if (argc == optind + 3) {
326                         opt.o_src = argv[optind++];
327                         opt.o_dst = argv[optind++];
328                 } else {
329                         rc = -EINVAL;
330                         CT_ERROR(rc, "--rebind requires 1 or 2 arguments");
331                         return rc;
332                 }
333                 break;
334         case CA_MAXSEQ:
335         default:
336                 /* just mount point */
337                 break;
338         }
339
340         if (argc != optind + 1) {
341                 rc = -EINVAL;
342                 CT_ERROR(rc, "no mount point specified");
343                 return rc;
344         }
345
346         opt.o_mnt = argv[optind];
347         opt.o_mnt_fd = -1;
348
349         CT_TRACE("action=%d src=%s dst=%s mount_point=%s",
350                  opt.o_action, opt.o_src, opt.o_dst, opt.o_mnt);
351
352         if (opt.o_hsm_root == NULL) {
353                 rc = -EINVAL;
354                 CT_ERROR(rc, "must specify a root directory for the backend");
355                 return rc;
356         }
357
358         if (opt.o_action == CA_IMPORT) {
359                 if (opt.o_src && opt.o_src[0] == '/') {
360                         rc = -EINVAL;
361                         CT_ERROR(rc,
362                                  "source path must be relative to HSM root");
363                         return rc;
364                 }
365
366                 if (opt.o_dst && opt.o_dst[0] != '/') {
367                         rc = -EINVAL;
368                         CT_ERROR(rc, "destination path must be absolute");
369                         return rc;
370                 }
371         }
372
373         return 0;
374 }
375
376 /* mkdir -p path */
377 static int ct_mkdir_p(const char *path)
378 {
379         char    *saved, *ptr;
380         int      rc;
381
382         ptr = strdup(path);
383         if (ptr == NULL)
384                 return -errno;
385
386         saved = ptr;
387         while (*ptr == '/')
388                 ptr++;
389
390         while ((ptr = strchr(ptr, '/')) != NULL) {
391                 *ptr = '\0';
392                 rc = mkdir(saved, DIR_PERM);
393                 *ptr = '/';
394                 if (rc < 0 && errno != EEXIST) {
395                         rc = -errno;
396                         CT_ERROR(rc, "cannot mkdir '%s'", path);
397                         free(saved);
398                         return rc;
399                 }
400                 ptr++;
401         }
402
403         free(saved);
404
405         return 0;
406 }
407
408 static int ct_save_stripe(int src_fd, const char *src, const char *dst)
409 {
410         char                     lov_file[PATH_MAX];
411         char                     lov_buf[XATTR_SIZE_MAX];
412         struct lov_user_md      *lum;
413         int                      rc;
414         int                      fd;
415         ssize_t                  xattr_size;
416
417         snprintf(lov_file, sizeof(lov_file), "%s.lov", dst);
418         CT_TRACE("saving stripe info of '%s' in %s", src, lov_file);
419
420         xattr_size = fgetxattr(src_fd, XATTR_LUSTRE_LOV, lov_buf,
421                                sizeof(lov_buf));
422         if (xattr_size < 0) {
423                 rc = -errno;
424                 CT_ERROR(rc, "cannot get stripe info on '%s'", src);
425                 return rc;
426         }
427
428         lum = (struct lov_user_md *)lov_buf;
429
430         if (lum->lmm_magic == LOV_USER_MAGIC_V1 ||
431             lum->lmm_magic == LOV_USER_MAGIC_V3) {
432                 /* Set stripe_offset to -1 so that it is not interpreted as a
433                  * hint on restore. */
434                 lum->lmm_stripe_offset = -1;
435         }
436
437         fd = open(lov_file, O_TRUNC | O_CREAT | O_WRONLY, FILE_PERM);
438         if (fd < 0) {
439                 rc = -errno;
440                 CT_ERROR(rc, "cannot open '%s'", lov_file);
441                 goto err_cleanup;
442         }
443
444         rc = write(fd, lum, xattr_size);
445         if (rc < 0) {
446                 rc = -errno;
447                 CT_ERROR(rc, "cannot write %zd bytes to '%s'",
448                          xattr_size, lov_file);
449                 close(fd);
450                 goto err_cleanup;
451         }
452
453         rc = close(fd);
454         if (rc < 0) {
455                 rc = -errno;
456                 CT_ERROR(rc, "cannot close '%s'", lov_file);
457                 goto err_cleanup;
458         }
459
460         return 0;
461
462 err_cleanup:
463         unlink(lov_file);
464
465         return rc;
466 }
467
468 static int ct_load_stripe(const char *src, void *lovea, size_t *lovea_size)
469 {
470         char     lov_file[PATH_MAX];
471         int      rc;
472         int      fd;
473
474         snprintf(lov_file, sizeof(lov_file), "%s.lov", src);
475         CT_TRACE("reading stripe rules from '%s' for '%s'", lov_file, src);
476
477         fd = open(lov_file, O_RDONLY);
478         if (fd < 0) {
479                 CT_ERROR(errno, "cannot open '%s'", lov_file);
480                 return -ENODATA;
481         }
482
483         rc = read(fd, lovea, *lovea_size);
484         if (rc < 0) {
485                 CT_ERROR(errno, "cannot read %zu bytes from '%s'",
486                          *lovea_size, lov_file);
487                 close(fd);
488                 return -ENODATA;
489         }
490
491         *lovea_size = rc;
492         close(fd);
493
494         return 0;
495 }
496
497 static int ct_restore_stripe(const char *src, const char *dst, int dst_fd,
498                              const void *lovea, size_t lovea_size)
499 {
500         int     rc;
501
502         rc = fsetxattr(dst_fd, XATTR_LUSTRE_LOV, lovea, lovea_size,
503                        XATTR_CREATE);
504         if (rc < 0) {
505                 rc = -errno;
506                 CT_ERROR(rc, "cannot set lov EA on '%s'", dst);
507         }
508
509         return rc;
510 }
511
512 static int ct_copy_data(struct hsm_copyaction_private *hcp, const char *src,
513                         const char *dst, int src_fd, int dst_fd,
514                         const struct hsm_action_item *hai, long hal_flags)
515 {
516         struct hsm_extent        he;
517         __u64                    offset = hai->hai_extent.offset;
518         struct stat              src_st;
519         struct stat              dst_st;
520         char                    *buf = NULL;
521         __u64                    write_total = 0;
522         __u64                    length = hai->hai_extent.length;
523         time_t                   last_report_time;
524         int                      rc = 0;
525         double                   start_ct_now = ct_now();
526         /* Bandwidth Control */
527         time_t                  start_time;
528         time_t                  now;
529         time_t                  last_bw_print;
530
531         if (fstat(src_fd, &src_st) < 0) {
532                 rc = -errno;
533                 CT_ERROR(rc, "cannot stat '%s'", src);
534                 return rc;
535         }
536
537         if (!S_ISREG(src_st.st_mode)) {
538                 rc = -EINVAL;
539                 CT_ERROR(rc, "'%s' is not a regular file", src);
540                 return rc;
541         }
542
543         if (hai->hai_extent.offset > (__u64)src_st.st_size) {
544                 rc = -EINVAL;
545                 CT_ERROR(rc, "Trying to start reading past end ("LPU64" > "
546                          "%jd) of '%s' source file", hai->hai_extent.offset,
547                          (intmax_t)src_st.st_size, src);
548                 return rc;
549         }
550
551         if (fstat(dst_fd, &dst_st) < 0) {
552                 rc = -errno;
553                 CT_ERROR(rc, "cannot stat '%s'", dst);
554                 return rc;
555         }
556
557         if (!S_ISREG(dst_st.st_mode)) {
558                 rc = -EINVAL;
559                 CT_ERROR(rc, "'%s' is not a regular file", dst);
560                 return rc;
561         }
562
563         /* Don't read beyond a given extent */
564         if (length > src_st.st_size - hai->hai_extent.offset)
565                 length = src_st.st_size - hai->hai_extent.offset;
566
567         start_time = last_bw_print = last_report_time = time(NULL);
568
569         he.offset = offset;
570         he.length = 0;
571         rc = llapi_hsm_action_progress(hcp, &he, length, 0);
572         if (rc < 0) {
573                 /* Action has been canceled or something wrong
574                  * is happening. Stop copying data. */
575                 CT_ERROR(rc, "progress ioctl for copy '%s'->'%s' failed",
576                          src, dst);
577                 goto out;
578         }
579
580         errno = 0;
581
582         buf = malloc(opt.o_chunk_size);
583         if (buf == NULL) {
584                 rc = -ENOMEM;
585                 goto out;
586         }
587
588         CT_TRACE("start copy of "LPU64" bytes from '%s' to '%s'",
589                  length, src, dst);
590
591         while (write_total < length) {
592                 ssize_t rsize;
593                 ssize_t wsize;
594                 int     chunk = (length - write_total > opt.o_chunk_size) ?
595                                  opt.o_chunk_size : length - write_total;
596
597                 rsize = pread(src_fd, buf, chunk, offset);
598                 if (rsize == 0)
599                         /* EOF */
600                         break;
601
602                 if (rsize < 0) {
603                         rc = -errno;
604                         CT_ERROR(rc, "cannot read from '%s'", src);
605                         break;
606                 }
607
608                 wsize = pwrite(dst_fd, buf, rsize, offset);
609                 if (wsize < 0) {
610                         rc = -errno;
611                         CT_ERROR(rc, "cannot write to '%s'", dst);
612                         break;
613                 }
614
615                 write_total += wsize;
616                 offset += wsize;
617
618                 now = time(NULL);
619                 /* sleep if needed, to honor bandwidth limits */
620                 if (opt.o_bandwidth != 0) {
621                         unsigned long long write_theory;
622
623                         write_theory = (now - start_time) * opt.o_bandwidth;
624
625                         if (write_theory < write_total) {
626                                 unsigned long long      excess;
627                                 struct timespec         delay;
628
629                                 excess = write_total - write_theory;
630
631                                 delay.tv_sec = excess / opt.o_bandwidth;
632                                 delay.tv_nsec = (excess % opt.o_bandwidth) *
633                                         NSEC_PER_SEC / opt.o_bandwidth;
634
635                                 if (now >= last_bw_print + opt.o_report_int) {
636                                         CT_TRACE("bandwith control: %lluB/s "
637                                                  "excess=%llu sleep for "
638                                                  "%lld.%09lds",
639                                                  opt.o_bandwidth, excess,
640                                                  (long long)delay.tv_sec,
641                                                  delay.tv_nsec);
642                                         last_bw_print = now;
643                                 }
644
645                                 do {
646                                         rc = nanosleep(&delay, &delay);
647                                 } while (rc < 0 && errno == EINTR);
648                                 if (rc < 0) {
649                                         CT_ERROR(errno, "delay for bandwidth "
650                                                  "control failed to sleep: "
651                                                  "residual=%lld.%09lds",
652                                                  (long long)delay.tv_sec,
653                                                  delay.tv_nsec);
654                                         rc = 0;
655                                 }
656                         }
657                 }
658
659                 now = time(NULL);
660                 if (now >= last_report_time + opt.o_report_int) {
661                         last_report_time = now;
662                         CT_TRACE("%%"LPU64" ", 100 * write_total / length);
663                         /* only give the length of the write since the last
664                          * progress report */
665                         he.length = offset - he.offset;
666                         rc = llapi_hsm_action_progress(hcp, &he, length, 0);
667                         if (rc < 0) {
668                                 /* Action has been canceled or something wrong
669                                  * is happening. Stop copying data. */
670                                 CT_ERROR(rc, "progress ioctl for copy"
671                                          " '%s'->'%s' failed", src, dst);
672                                 goto out;
673                         }
674                         he.offset = offset;
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 successful */
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