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