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