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