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