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