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