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