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