Whamcloud - gitweb
LU-10114 hsm: increase upper limit of maximum HSM backends registered with MDT
[fs/lustre-release.git] / lustre / utils / liblustreapi_hsm.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * (C) Copyright 2012 Commissariat a l'energie atomique et aux energies
7  *     alternatives
8  *
9  * Copyright (c) 2013, 2017, Intel Corporation.
10  *
11  * All rights reserved. This program and the accompanying materials
12  * are made available under the terms of the GNU Lesser General Public License
13  * (LGPL) version 2.1 or (at your discretion) any later version.
14  * (LGPL) version 2.1 accompanies this distribution, and is available at
15  * http://www.gnu.org/licenses/lgpl-2.1.html
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20  * Lesser General Public License for more details.
21  *
22  * LGPL HEADER END
23  */
24 /*
25  * lustre/utils/liblustreapi_hsm.c
26  *
27  * lustreapi library for hsm calls
28  *
29  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
30  * Author: JC Lafoucriere <jacques-charles.lafoucriere@cea.fr>
31  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
32  * Author: Henri Doreau <henri.doreau@cea.fr>
33  */
34
35 #include <fcntl.h>
36 #include <stdlib.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <stddef.h>
40 #include <sys/ioctl.h>
41 #include <unistd.h>
42 #include <malloc.h>
43 #include <errno.h>
44 #include <dirent.h>
45 #include <stdarg.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <time.h>
50 #include <utime.h>
51 #include <sys/syscall.h>
52 #include <fnmatch.h>
53 #include <signal.h>
54 #ifdef HAVE_LINUX_UNISTD_H
55 #include <linux/unistd.h>
56 #else
57 #include <unistd.h>
58 #endif
59
60 #include <linux/lnet/lnetctl.h>
61 #include <lustre/lustreapi.h>
62 #include "lustreapi_internal.h"
63
64 #define OPEN_BY_FID_PATH dot_lustre_name"/fid"
65
66 /****** HSM Copytool API ********/
67 #define CT_PRIV_MAGIC 0xC0BE2001
68 struct hsm_copytool_private {
69         int                              magic;
70         char                            *mnt;
71         struct kuc_hdr                  *kuch;
72         int                              mnt_fd;
73         int                              open_by_fid_fd;
74         struct lustre_kernelcomm        *kuc;
75 };
76
77 #define CP_PRIV_MAGIC 0x19880429
78 struct hsm_copyaction_private {
79         __u32                                    magic;
80         __u32                                    source_fd;
81         __s32                                    data_fd;
82         const struct hsm_copytool_private       *ct_priv;
83         struct hsm_copy                          copy;
84         lstat_t                                  stat;
85 };
86
87 enum ct_progress_type {
88         CT_START        = 0,
89         CT_RUNNING      = 50,
90         CT_FINISH       = 100,
91         CT_CANCEL       = 150,
92         CT_ERROR        = 175
93 };
94
95 enum ct_event {
96         CT_REGISTER             = 1,
97         CT_UNREGISTER           = 2,
98         CT_ARCHIVE_START        = HSMA_ARCHIVE,
99         CT_ARCHIVE_RUNNING      = HSMA_ARCHIVE + CT_RUNNING,
100         CT_ARCHIVE_FINISH       = HSMA_ARCHIVE + CT_FINISH,
101         CT_ARCHIVE_CANCEL       = HSMA_ARCHIVE + CT_CANCEL,
102         CT_ARCHIVE_ERROR        = HSMA_ARCHIVE + CT_ERROR,
103         CT_RESTORE_START        = HSMA_RESTORE,
104         CT_RESTORE_RUNNING      = HSMA_RESTORE + CT_RUNNING,
105         CT_RESTORE_FINISH       = HSMA_RESTORE + CT_FINISH,
106         CT_RESTORE_CANCEL       = HSMA_RESTORE + CT_CANCEL,
107         CT_RESTORE_ERROR        = HSMA_RESTORE + CT_ERROR,
108         CT_REMOVE_START         = HSMA_REMOVE,
109         CT_REMOVE_RUNNING       = HSMA_REMOVE + CT_RUNNING,
110         CT_REMOVE_FINISH        = HSMA_REMOVE + CT_FINISH,
111         CT_REMOVE_CANCEL        = HSMA_REMOVE + CT_CANCEL,
112         CT_REMOVE_ERROR         = HSMA_REMOVE + CT_ERROR,
113         CT_EVENT_MAX
114 };
115
116 /* initialized in llapi_hsm_register_event_fifo() */
117 static int llapi_hsm_event_fd = -1;
118 static bool created_hsm_event_fifo;
119
120 static inline const char *llapi_hsm_ct_ev2str(int type)
121 {
122         switch (type) {
123         case CT_REGISTER:
124                 return "REGISTER";
125         case CT_UNREGISTER:
126                 return "UNREGISTER";
127         case CT_ARCHIVE_START:
128                 return "ARCHIVE_START";
129         case CT_ARCHIVE_RUNNING:
130                 return "ARCHIVE_RUNNING";
131         case CT_ARCHIVE_FINISH:
132                 return "ARCHIVE_FINISH";
133         case CT_ARCHIVE_CANCEL:
134                 return "ARCHIVE_CANCEL";
135         case CT_ARCHIVE_ERROR:
136                 return "ARCHIVE_ERROR";
137         case CT_RESTORE_START:
138                 return "RESTORE_START";
139         case CT_RESTORE_RUNNING:
140                 return "RESTORE_RUNNING";
141         case CT_RESTORE_FINISH:
142                 return "RESTORE_FINISH";
143         case CT_RESTORE_CANCEL:
144                 return "RESTORE_CANCEL";
145         case CT_RESTORE_ERROR:
146                 return "RESTORE_ERROR";
147         case CT_REMOVE_START:
148                 return "REMOVE_START";
149         case CT_REMOVE_RUNNING:
150                 return "REMOVE_RUNNING";
151         case CT_REMOVE_FINISH:
152                 return "REMOVE_FINISH";
153         case CT_REMOVE_CANCEL:
154                 return "REMOVE_CANCEL";
155         case CT_REMOVE_ERROR:
156                 return "REMOVE_ERROR";
157         default:
158                 llapi_err_noerrno(LLAPI_MSG_ERROR,
159                                   "Unknown event type: %d", type);
160                 return NULL;
161         }
162 }
163
164 /**
165  * Writes a JSON event to the monitor FIFO. Noop if no FIFO has been
166  * registered.
167  *
168  * \param event              A list of llapi_json_items comprising a
169  *                           single JSON-formatted event.
170  *
171  * \retval 0 on success.
172  * \retval -errno on error.
173  */
174 static int llapi_hsm_write_json_event(struct llapi_json_item_list **event)
175 {
176         int                             rc;
177         char                            time_string[40];
178         char                            json_buf[PIPE_BUF];
179         FILE                            *buf_file;
180         time_t                          event_time = time(0);
181         struct tm                       time_components;
182         struct llapi_json_item_list     *json_items;
183
184         /* Noop unless the event fd was initialized */
185         if (llapi_hsm_event_fd < 0)
186                 return 0;
187
188         if (event == NULL || *event == NULL)
189                 return -EINVAL;
190
191         json_items = *event;
192
193         localtime_r(&event_time, &time_components);
194
195         if (strftime(time_string, sizeof(time_string), "%Y-%m-%d %T %z",
196                      &time_components) == 0) {
197                 rc = -EINVAL;
198                 llapi_error(LLAPI_MSG_ERROR, rc, "strftime() failed");
199                 return rc;
200         }
201
202         rc = llapi_json_add_item(&json_items, "event_time", LLAPI_JSON_STRING,
203                                  time_string);
204         if (rc < 0) {
205                 llapi_error(LLAPI_MSG_ERROR, -rc, "error in "
206                             "llapi_json_add_item()");
207                 return rc;
208         }
209
210         buf_file = fmemopen(json_buf, sizeof(json_buf), "w");
211         if (buf_file == NULL)
212                 return -errno;
213
214         rc = llapi_json_write_list(event, buf_file);
215         if (rc < 0) {
216                 fclose(buf_file);
217                 return rc;
218         }
219
220         fclose(buf_file);
221
222         if (write(llapi_hsm_event_fd, json_buf, strlen(json_buf)) < 0) {
223                 /* Ignore write failures due to missing reader. */
224                 if (errno != EPIPE)
225                         return -errno;
226         }
227
228         return 0;
229 }
230
231 /**
232  * Hook for llapi_hsm_copytool_register and llapi_hsm_copytool_unregister
233  * to generate JSON events suitable for consumption by a copytool
234  * monitoring process.
235  *
236  * \param priv               Opaque private control structure.
237  * \param event_type         The type of event (register or unregister).
238  *
239  * \retval 0 on success.
240  * \retval -errno on error.
241  */
242 static int llapi_hsm_log_ct_registration(struct hsm_copytool_private **priv,
243                                          __u32 event_type)
244 {
245         int                             rc;
246         char                            agent_uuid[UUID_MAX];
247         struct hsm_copytool_private     *ct;
248         struct llapi_json_item_list     *json_items;
249
250         /* Noop unless the event fd was initialized */
251         if (llapi_hsm_event_fd < 0)
252                 return 0;
253
254         if (priv == NULL || *priv == NULL)
255                 return -EINVAL;
256
257         ct = *priv;
258         if (ct->magic != CT_PRIV_MAGIC)
259                 return -EINVAL;
260
261         if (event_type != CT_REGISTER && event_type != CT_UNREGISTER)
262                 return -EINVAL;
263
264         rc = llapi_json_init_list(&json_items);
265         if (rc < 0)
266                 goto err;
267
268         rc = llapi_get_agent_uuid(ct->mnt, agent_uuid, sizeof(agent_uuid));
269         if (rc < 0)
270                 goto err;
271         llapi_chomp_string(agent_uuid);
272
273         rc = llapi_json_add_item(&json_items, "uuid", LLAPI_JSON_STRING,
274                                  agent_uuid);
275         if (rc < 0)
276                 goto err;
277
278         rc = llapi_json_add_item(&json_items, "mount_point", LLAPI_JSON_STRING,
279                                  ct->mnt);
280         if (rc < 0)
281                 goto err;
282
283         rc = llapi_json_add_item(&json_items, "archive", LLAPI_JSON_INTEGER,
284                                  &ct->kuc->lk_data_count);
285         if (rc < 0)
286                 goto err;
287
288         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
289                                  (char *)llapi_hsm_ct_ev2str(event_type));
290         if (rc < 0)
291                 goto err;
292
293         rc = llapi_hsm_write_json_event(&json_items);
294         if (rc < 0)
295                 goto err;
296
297         goto out_free;
298
299 err:
300         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
301                     "llapi_hsm_log_ct_registration()");
302
303 out_free:
304         if (json_items != NULL)
305                 llapi_json_destroy_list(&json_items);
306
307         return rc;
308 }
309
310 /**
311  * Given a copytool progress update, construct a JSON event suitable for
312  * consumption by a copytool monitoring process.
313  *
314  * Examples of various events generated here and written by
315  * llapi_hsm_write_json_event:
316  *
317  * Copytool registration and deregistration:
318  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "REGISTER",
319  *  "archive": 0, "mount_point": "/mnt/lustre",
320  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
321  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "UNREGISTER",
322  *  "archive": 0, "mount_point": "/mnt/lustre",
323  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
324  *
325  * An archive action, start to completion:
326  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "ARCHIVE_START",
327  *  "total_bytes": 0, "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
328  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
329  * {"event_time": "2014-02-26 14:50:18 -0500", "event_type": "ARCHIVE_RUNNING",
330  *  "current_bytes": 5242880, "total_bytes": 39000000,
331  *  "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
332  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
333  * {"event_time": "2014-02-26 14:50:50 -0500", "event_type": "ARCHIVE_FINISH",
334  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
335  *
336  * A log message:
337  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "LOGGED_MESSAGE",
338  *  "level": "INFO",
339  *  "message": "lhsmtool_posix[42]: copytool fs=lustre archive#=2 item_count=1"}
340  *
341  * \param hcp                Opaque action handle returned by
342  *                           llapi_hsm_action_start.
343  * \param hai                The hsm_action_item describing the request.
344  * \param progress_type      The ct_progress_type describing the update.
345  * \param total              The total expected bytes for the request.
346  * \param current            The current copied byte count for the request.
347  *
348  * \retval 0 on success.
349  * \retval -errno on error.
350  */
351 static int llapi_hsm_log_ct_progress(struct hsm_copyaction_private **phcp,
352                                      const struct hsm_action_item *hai,
353                                      __u32 progress_type,
354                                      __u64 total, __u64 current)
355 {
356         int                             rc;
357         int                             linkno = 0;
358         long long                       recno = -1;
359         char                            lustre_path[PATH_MAX];
360         char                            strfid[FID_NOBRACE_LEN + 1];
361         struct hsm_copyaction_private   *hcp;
362         struct llapi_json_item_list     *json_items;
363
364         /* Noop unless the event fd was initialized */
365         if (llapi_hsm_event_fd < 0)
366                 return 0;
367
368         if (phcp == NULL || *phcp == NULL)
369                 return -EINVAL;
370
371         hcp = *phcp;
372
373         rc = llapi_json_init_list(&json_items);
374         if (rc < 0)
375                 goto err;
376
377         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_dfid));
378         rc = llapi_json_add_item(&json_items, "data_fid",
379                                  LLAPI_JSON_STRING, strfid);
380         if (rc < 0)
381                 goto err;
382
383         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_fid));
384         rc = llapi_json_add_item(&json_items, "source_fid",
385                                  LLAPI_JSON_STRING, strfid);
386         if (rc < 0)
387                 goto err;
388
389         if (hcp->copy.hc_errval == ECANCELED) {
390                 progress_type = CT_CANCEL;
391                 goto cancel;
392         }
393
394         if (hcp->copy.hc_errval != 0) {
395                 progress_type = CT_ERROR;
396
397                 rc = llapi_json_add_item(&json_items, "errno",
398                                          LLAPI_JSON_INTEGER,
399                                          &hcp->copy.hc_errval);
400                 if (rc < 0)
401                         goto err;
402
403                 rc = llapi_json_add_item(&json_items, "error",
404                                          LLAPI_JSON_STRING,
405                                          strerror(hcp->copy.hc_errval));
406                 if (rc < 0)
407                         goto err;
408
409                 goto cancel;
410         }
411
412         /* lustre_path isn't available after a restore completes */
413         /* total_bytes isn't available after a restore or archive completes */
414         if (progress_type != CT_FINISH) {
415                 rc = llapi_fid2path(hcp->ct_priv->mnt, strfid, lustre_path,
416                                     sizeof(lustre_path), &recno, &linkno);
417                 if (rc < 0)
418                         goto err;
419
420                 rc = llapi_json_add_item(&json_items, "lustre_path",
421                                          LLAPI_JSON_STRING, lustre_path);
422                 if (rc < 0)
423                         goto err;
424
425                 rc = llapi_json_add_item(&json_items, "total_bytes",
426                                          LLAPI_JSON_BIGNUM, &total);
427                 if (rc < 0)
428                         goto err;
429         }
430
431         if (progress_type == CT_RUNNING) {
432                 rc = llapi_json_add_item(&json_items, "current_bytes",
433                                          LLAPI_JSON_BIGNUM, &current);
434                 if (rc < 0)
435                         goto err;
436         }
437
438 cancel:
439         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
440                                  (char *)llapi_hsm_ct_ev2str(hai->hai_action +
441                                                              progress_type));
442         if (rc < 0)
443                 goto err;
444
445         rc = llapi_hsm_write_json_event(&json_items);
446         if (rc < 0)
447                 goto err;
448
449         goto out_free;
450
451 err:
452         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
453                     "llapi_hsm_log_ct_progress()");
454
455 out_free:
456         if (json_items != NULL)
457                 llapi_json_destroy_list(&json_items);
458
459         return rc;
460 }
461
462 /**
463  * Given a path to a FIFO, create a filehandle for nonblocking writes to it.
464  * Intended to be used for copytool monitoring processes that read an
465  * event stream from the FIFO. Events written in the absence of a reader
466  * are lost.
467  *
468  * \param path               Path to monitor FIFO.
469  *
470  * \retval 0 on success.
471  * \retval -errno on error.
472  */
473 int llapi_hsm_register_event_fifo(const char *path)
474 {
475         int read_fd;
476         struct stat statbuf;
477         struct sigaction ignore_action;
478         int rc;
479
480         /* Create the FIFO if necessary. */
481         if ((mkfifo(path, 0644) < 0) && (errno != EEXIST)) {
482                 llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed", path);
483                 return -errno;
484         }
485         if (errno == EEXIST) {
486                 if (stat(path, &statbuf) < 0) {
487                         llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed",
488                                     path);
489                         return -errno;
490                 }
491                 if (!S_ISFIFO(statbuf.st_mode) ||
492                     ((statbuf.st_mode & 0777) != 0644)) {
493                         llapi_error(LLAPI_MSG_ERROR, errno, "%s exists but is "
494                                     "not a pipe or has a wrong mode", path);
495                         return -errno;
496                 }
497         } else {
498                 created_hsm_event_fifo = true;
499         }
500
501         /* Open the FIFO for read so that the subsequent open for write
502          * doesn't immediately fail. */
503         read_fd = open(path, O_RDONLY | O_NONBLOCK);
504         if (read_fd < 0) {
505                 llapi_error(LLAPI_MSG_ERROR, errno,
506                             "cannot open(%s) for read", path);
507                 return -errno;
508         }
509
510         /* Open the FIFO for writes, but don't block on waiting
511          * for a reader. */
512         llapi_hsm_event_fd = open(path, O_WRONLY | O_NONBLOCK);
513         rc = -errno;
514
515         /* Now close the reader. An external monitoring process can
516          * now open the FIFO for reads. If no reader comes along the
517          * events are lost. NOTE: Only one reader at a time! */
518         close(read_fd);
519
520         if (llapi_hsm_event_fd < 0) {
521                 llapi_error(LLAPI_MSG_ERROR, -rc,
522                             "cannot open(%s) for write", path);
523                 return rc;
524         }
525
526         /* Ignore SIGPIPEs -- can occur if the reader goes away. */
527         memset(&ignore_action, 0, sizeof(ignore_action));
528         ignore_action.sa_handler = SIG_IGN;
529         sigemptyset(&ignore_action.sa_mask);
530         sigaction(SIGPIPE, &ignore_action, NULL);
531
532         return 0;
533 }
534
535 /**
536  * Given a path to a FIFO, close its filehandle and delete the FIFO.
537  *
538  * \param path               Path to monitor FIFO.
539  *
540  * \retval 0 on success.
541  * \retval -errno on error.
542  */
543 int llapi_hsm_unregister_event_fifo(const char *path)
544 {
545         /* Noop unless the event fd was initialized */
546         if (llapi_hsm_event_fd < 0)
547                 return 0;
548
549         if (close(llapi_hsm_event_fd) < 0)
550                 return -errno;
551
552         if (created_hsm_event_fifo) {
553                 unlink(path);
554                 created_hsm_event_fifo = false;
555         }
556
557         llapi_hsm_event_fd = -1;
558
559         return 0;
560 }
561
562 /**
563  * Custom logging callback to be used when a monitoring FIFO has been
564  * registered. Formats log entries as JSON events suitable for
565  * consumption by a copytool monitoring process.
566  *
567  * \param level              The message loglevel.
568  * \param _rc                The returncode associated with the message.
569  * \param fmt                The message format string.
570  * \param args               Arguments to be formatted by the format string.
571  *
572  * \retval None.
573  */
574 void llapi_hsm_log_error(enum llapi_message_level level, int _rc,
575                          const char *fmt, va_list args)
576 {
577         int                             rc;
578         int                             msg_len;
579         int                             real_level;
580         char                            *msg = NULL;
581         va_list                         args2;
582         struct llapi_json_item_list     *json_items;
583
584         /* Noop unless the event fd was initialized */
585         if (llapi_hsm_event_fd < 0)
586                 return;
587
588         rc = llapi_json_init_list(&json_items);
589         if (rc < 0)
590                 goto err;
591
592         if ((level & LLAPI_MSG_NO_ERRNO) == 0) {
593                 rc = llapi_json_add_item(&json_items, "errno",
594                                          LLAPI_JSON_INTEGER,
595                                          &_rc);
596                 if (rc < 0)
597                         goto err;
598
599                 rc = llapi_json_add_item(&json_items, "error",
600                                          LLAPI_JSON_STRING,
601                                          strerror(abs(_rc)));
602                 if (rc < 0)
603                         goto err;
604         }
605
606         va_copy(args2, args);
607         msg_len = vsnprintf(NULL, 0, fmt, args2) + 1;
608         va_end(args2);
609         if (msg_len >= 0) {
610                 msg = (char *) alloca(msg_len);
611                 if (msg == NULL) {
612                         rc = -ENOMEM;
613                         goto err;
614                 }
615
616                 rc = vsnprintf(msg, msg_len, fmt, args);
617                 if (rc < 0)
618                         goto err;
619
620                 rc = llapi_json_add_item(&json_items, "message",
621                                          LLAPI_JSON_STRING,
622                                          msg);
623                 if (rc < 0)
624                         goto err;
625         } else {
626                 rc = llapi_json_add_item(&json_items, "message",
627                                          LLAPI_JSON_STRING,
628                                          "INTERNAL ERROR: message failed");
629                 if (rc < 0)
630                         goto err;
631         }
632
633         real_level = level & LLAPI_MSG_NO_ERRNO;
634         real_level = real_level > 0 ? level - LLAPI_MSG_NO_ERRNO : level;
635
636         rc = llapi_json_add_item(&json_items, "level", LLAPI_JSON_STRING,
637                                  (void *)llapi_msg_level2str(real_level));
638         if (rc < 0)
639                 goto err;
640
641         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
642                                  "LOGGED_MESSAGE");
643         if (rc < 0)
644                 goto err;
645
646         rc = llapi_hsm_write_json_event(&json_items);
647         if (rc < 0)
648                 goto err;
649
650         goto out_free;
651
652 err:
653         /* Write directly to stderr to avoid llapi_error, which now
654          * emits JSON event messages. */
655         fprintf(stderr, "\nFATAL ERROR IN llapi_hsm_log_error(): rc %d,", rc);
656
657 out_free:
658         if (json_items != NULL)
659                 llapi_json_destroy_list(&json_items);
660
661         return;
662 }
663
664 /** Register a copytool
665  * \param[out] priv             Opaque private control structure
666  * \param mnt                   Lustre filesystem mount point
667  * \param archive_count         Number of valid archive IDs in \a archives
668  * \param archives              Which archive numbers this copytool is
669  *                              responsible for
670  * \param rfd_flags             flags applied to read fd of pipe
671  *                              (e.g. O_NONBLOCK)
672  *
673  * \retval 0 on success.
674  * \retval -errno on error.
675  */
676 int llapi_hsm_copytool_register(struct hsm_copytool_private **priv,
677                                 const char *mnt, int archive_count,
678                                 int *archives, int rfd_flags)
679 {
680         struct hsm_copytool_private     *ct;
681         int                              rc;
682
683         if (archive_count > 0 && archives == NULL) {
684                 llapi_err_noerrno(LLAPI_MSG_ERROR,
685                                   "NULL archive numbers");
686                 return -EINVAL;
687         }
688
689         for (rc = 0; rc < archive_count; rc++) {
690                 /* in the list we have an all archive wildcard
691                  * so move to all archives mode
692                  */
693                 if (archives[rc] == 0) {
694                         archive_count = 0;
695                         break;
696                 }
697         }
698
699         ct = calloc(1, sizeof(*ct));
700         if (ct == NULL)
701                 return -ENOMEM;
702
703         ct->magic = CT_PRIV_MAGIC;
704         ct->mnt_fd = -1;
705         ct->open_by_fid_fd = -1;
706
707         ct->mnt = strdup(mnt);
708         if (ct->mnt == NULL) {
709                 rc = -ENOMEM;
710                 goto out_err;
711         }
712
713         ct->kuch = calloc(1, HAL_MAXSIZE + sizeof(*ct->kuch));
714         if (ct->kuch == NULL) {
715                 rc = -ENOMEM;
716                 goto out_err;
717         }
718
719         ct->mnt_fd = open(ct->mnt, O_RDONLY);
720         if (ct->mnt_fd < 0) {
721                 rc = -errno;
722                 goto out_err;
723         }
724
725         ct->open_by_fid_fd = openat(ct->mnt_fd, OPEN_BY_FID_PATH, O_RDONLY);
726         if (ct->open_by_fid_fd < 0) {
727                 rc = -errno;
728                 goto out_err;
729         }
730
731         ct->kuc = malloc(sizeof(*ct) + archive_count * sizeof(__u32));
732         if (ct->kuc == NULL) {
733                 rc = -ENOMEM;
734                 goto out_err;
735         }
736
737         ct->kuc->lk_rfd = LK_NOFD;
738         ct->kuc->lk_wfd = LK_NOFD;
739
740         rc = libcfs_ukuc_start(ct->kuc, KUC_GRP_HSM, rfd_flags);
741         if (rc < 0)
742                 goto out_free_kuc;
743
744         ct->kuc->lk_flags = LK_FLG_DATANR;
745         ct->kuc->lk_data_count = archive_count;
746         for (rc = 0; rc < archive_count; rc++) {
747                 if (archives[rc] < 0) {
748                         llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when "
749                                           "archive id >= 0 is supported",
750                                           archives[rc]);
751                         rc = -EINVAL;
752                         goto out_kuc;
753                 }
754
755                 ct->kuc->lk_data[rc] = archives[rc];
756         }
757
758         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, ct->kuc);
759         if (rc < 0) {
760                 rc = -errno;
761                 llapi_error(LLAPI_MSG_ERROR, rc,
762                             "cannot start copytool on '%s'", mnt);
763                 goto out_kuc;
764         }
765
766         llapi_hsm_log_ct_registration(&ct, CT_REGISTER);
767
768         /* Only the kernel reference keeps the write side open */
769         close(ct->kuc->lk_wfd);
770         ct->kuc->lk_wfd = LK_NOFD;
771         *priv = ct;
772
773         return 0;
774
775 out_kuc:
776         /* cleanup the kuc channel */
777         libcfs_ukuc_stop(ct->kuc);
778
779 out_free_kuc:
780         free(ct->kuc);
781
782 out_err:
783         if (!(ct->mnt_fd < 0))
784                 close(ct->mnt_fd);
785
786         if (!(ct->open_by_fid_fd < 0))
787                 close(ct->open_by_fid_fd);
788
789         free(ct->mnt);
790
791         free(ct->kuch);
792
793         free(ct);
794
795         return rc;
796 }
797
798 /** Deregister a copytool
799  * Note: under Linux, until llapi_hsm_copytool_unregister is called
800  * (or the program is killed), the libcfs module will be referenced
801  * and unremovable, even after Lustre services stop.
802  */
803 int llapi_hsm_copytool_unregister(struct hsm_copytool_private **priv)
804 {
805         struct hsm_copytool_private *ct;
806
807         if (priv == NULL || *priv == NULL)
808                 return -EINVAL;
809
810         ct = *priv;
811         if (ct->magic != CT_PRIV_MAGIC)
812                 return -EINVAL;
813
814         /* Close the read side of the KUC pipe. This should be done
815          * before unregistering to avoid deadlock: a ldlm_cb thread
816          * enters libcfs_kkuc_group_put() acquires kg_sem and blocks
817          * in pipe_write() due to full pipe; then we attempt to
818          * unregister and block on kg_sem. */
819         libcfs_ukuc_stop(ct->kuc);
820
821         /* Tell the kernel to stop sending us messages */
822         ct->kuc->lk_flags = LK_FLG_STOP;
823         ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, ct->kuc);
824
825         llapi_hsm_log_ct_registration(&ct, CT_UNREGISTER);
826
827         close(ct->open_by_fid_fd);
828         close(ct->mnt_fd);
829         free(ct->mnt);
830         free(ct->kuch);
831         free(ct->kuc);
832         free(ct);
833         *priv = NULL;
834
835         return 0;
836 }
837
838 /** Returns a file descriptor to poll/select on.
839  * \param ct Opaque private control structure
840  * \retval -EINVAL on error
841  * \retval the file descriptor for reading HSM events from the kernel
842  */
843 int llapi_hsm_copytool_get_fd(struct hsm_copytool_private *ct)
844 {
845         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
846                 return -EINVAL;
847
848         return libcfs_ukuc_get_rfd(ct->kuc);
849 }
850
851 /** Wait for the next hsm_action_list
852  * \param ct Opaque private control structure
853  * \param halh Action list handle, will be allocated here
854  * \param msgsize Number of bytes in the message, will be set here
855  * \return 0 valid message received; halh and msgsize are set
856  *         <0 error code
857  * Note: The application must not call llapi_hsm_copytool_recv until it has
858  * cleared the data in ct->kuch from the previous call.
859  */
860 int llapi_hsm_copytool_recv(struct hsm_copytool_private *ct,
861                             struct hsm_action_list **halh, int *msgsize)
862 {
863         struct kuc_hdr          *kuch;
864         struct hsm_action_list  *hal;
865         int                      rc = 0;
866
867         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
868                 return -EINVAL;
869
870         if (halh == NULL || msgsize == NULL)
871                 return -EINVAL;
872
873         kuch = ct->kuch;
874
875 repeat:
876         rc = libcfs_ukuc_msg_get(ct->kuc, (char *)kuch,
877                                  HAL_MAXSIZE + sizeof(*kuch),
878                                  KUC_TRANSPORT_HSM);
879         if (rc < 0)
880                 goto out_err;
881
882         /* Handle generic messages */
883         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
884             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
885                 rc = -ESHUTDOWN;
886                 goto out_err;
887         }
888
889         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
890             kuch->kuc_msgtype != HMT_ACTION_LIST) {
891                 llapi_err_noerrno(LLAPI_MSG_ERROR,
892                                   "Unknown HSM message type %d:%d\n",
893                                   kuch->kuc_transport, kuch->kuc_msgtype);
894                 rc = -EPROTO;
895                 goto out_err;
896         }
897
898         if (kuch->kuc_msglen < sizeof(*kuch) + sizeof(*hal)) {
899                 llapi_err_noerrno(LLAPI_MSG_ERROR, "Short HSM message %d",
900                                   kuch->kuc_msglen);
901                 rc = -EPROTO;
902                 goto out_err;
903         }
904
905         /* Our message is a hsm_action_list. Use pointer math to skip
906         * kuch_hdr and point directly to the message payload.
907         */
908         hal = (struct hsm_action_list *)(kuch + 1);
909
910         /* Check that we have registered for this archive #
911          * if 0 registered, we serve any archive */
912         if (ct->kuc != NULL && ct->kuc->lk_data_count != 0) {
913                 int i;
914
915                 for (i = 0; i < ct->kuc->lk_data_count; i++) {
916                         if (hal->hal_archive_id == ct->kuc->lk_data[i])
917                                 break;
918                 }
919
920                 if (i >= ct->kuc->lk_data_count)
921                         goto repeat;
922         }
923
924         *halh = hal;
925         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
926         return 0;
927
928 out_err:
929         *halh = NULL;
930         *msgsize = 0;
931         return rc;
932 }
933
934 /** Get parent path from mount point and fid.
935  *
936  * \param mnt        Filesystem root path.
937  * \param fid        Object FID.
938  * \param parent     Destination buffer.
939  * \param parent_len Destination buffer size.
940  * \return 0 on success.
941  */
942 static int fid_parent(const char *mnt, const struct lu_fid *fid, char *parent,
943                       size_t parent_len)
944 {
945         int              rc;
946         int              linkno = 0;
947         long long        recno = -1;
948         char             file[PATH_MAX];
949         char             strfid[FID_NOBRACE_LEN + 1];
950         char            *ptr;
951
952         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(fid));
953
954         rc = llapi_fid2path(mnt, strfid, file, sizeof(file),
955                             &recno, &linkno);
956         if (rc < 0)
957                 return rc;
958
959         /* fid2path returns a relative path */
960         rc = snprintf(parent, parent_len, "%s/%s", mnt, file);
961         if (rc >= parent_len)
962                 return -ENAMETOOLONG;
963
964         /* remove file name */
965         ptr = strrchr(parent, '/');
966         if (ptr == NULL || ptr == parent) {
967                 rc = -EINVAL;
968         } else {
969                 *ptr = '\0';
970                 rc = 0;
971         }
972
973         return rc;
974 }
975
976 static int ct_open_by_fid(const struct hsm_copytool_private *ct,
977                           const struct lu_fid *fid, int open_flags)
978 {
979         char fid_name[FID_NOBRACE_LEN + 1];
980         int fd;
981
982         snprintf(fid_name, sizeof(fid_name), DFID_NOBRACE, PFID(fid));
983
984         fd = openat(ct->open_by_fid_fd, fid_name, open_flags);
985         return fd < 0 ? -errno : fd;
986 }
987
988 /**
989  * Get metadata attributes of file by FID.
990  *
991  * Use the IOC_MDC_GETFILEINFO ioctl (to send a MDS_GETATTR_NAME RPC)
992  * to get the attributes of the file identified by \a fid. This
993  * returns only the attributes stored on the MDT and avoids taking
994  * layout locks or accessing OST objects. It also bypasses the inode
995  * cache. Attributes are returned in \a st.
996  */
997 static int ct_md_getattr(const struct hsm_copytool_private *ct,
998                          const struct lu_fid *fid,
999                          lstat_t *st)
1000 {
1001         struct lov_user_mds_data *lmd;
1002         char fname[FID_NOBRACE_LEN + 1] = "";
1003         size_t lmd_size;
1004         int rc;
1005
1006         rc = snprintf(fname, sizeof(fname), DFID_NOBRACE, PFID(fid));
1007         if (rc < 0)
1008                 return rc;
1009         if (rc >= sizeof(fname) || rc == 0)
1010                 return -EINVAL;
1011
1012         lmd_size = sizeof(lmd->lmd_st) +
1013                 lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
1014
1015         if (lmd_size < sizeof(lmd->lmd_st) + XATTR_SIZE_MAX)
1016                 lmd_size = sizeof(lmd->lmd_st) + XATTR_SIZE_MAX;
1017
1018         lmd = malloc(lmd_size);
1019         if (lmd == NULL)
1020                 return -ENOMEM;
1021
1022         rc = get_lmd_info_fd(fname, ct->open_by_fid_fd, -1,
1023                              lmd, lmd_size, GET_LMD_INFO);
1024         if (rc)
1025                 goto out;
1026
1027         *st = lmd->lmd_st;
1028 out:
1029         free(lmd);
1030
1031         return rc;
1032 }
1033
1034 /** Create the destination volatile file for a restore operation.
1035  *
1036  * \param hcp        Private copyaction handle.
1037  * \param mdt_index  MDT index where to create the volatile file.
1038  * \param flags      Volatile file creation flags.
1039  * \return 0 on success.
1040  */
1041 static int create_restore_volatile(struct hsm_copyaction_private *hcp,
1042                                    int mdt_index, int open_flags)
1043 {
1044         int                      rc;
1045         int                      fd;
1046         char                     parent[PATH_MAX + 1];
1047         const char              *mnt = hcp->ct_priv->mnt;
1048         struct hsm_action_item  *hai = &hcp->copy.hc_hai;
1049
1050         rc = fid_parent(mnt, &hai->hai_fid, parent, sizeof(parent));
1051         if (rc < 0) {
1052                 /* fid_parent() failed, try to keep on going */
1053                 llapi_error(LLAPI_MSG_ERROR, rc,
1054                             "cannot get parent path to restore "DFID" "
1055                             "using '%s'", PFID(&hai->hai_fid), mnt);
1056                 snprintf(parent, sizeof(parent), "%s", mnt);
1057         }
1058
1059         fd = llapi_create_volatile_idx(parent, mdt_index, open_flags);
1060         if (fd < 0)
1061                 return fd;
1062
1063         rc = fchown(fd, hcp->stat.st_uid, hcp->stat.st_gid);
1064         if (rc < 0)
1065                 goto err_cleanup;
1066
1067         rc = llapi_fd2fid(fd, &hai->hai_dfid);
1068         if (rc < 0)
1069                 goto err_cleanup;
1070
1071         hcp->data_fd = fd;
1072
1073         return 0;
1074
1075 err_cleanup:
1076         hcp->data_fd = -1;
1077         close(fd);
1078
1079         return rc;
1080 }
1081
1082 /** Start processing an HSM action.
1083  * Should be called by copytools just before starting handling a request.
1084  * It could be skipped if copytool only want to directly report an error,
1085  * \see llapi_hsm_action_end().
1086  *
1087  * \param hcp                Opaque action handle to be passed to
1088  *                           llapi_hsm_action_progress and llapi_hsm_action_end.
1089  * \param ct                 Copytool handle acquired at registration.
1090  * \param hai                The hsm_action_item describing the request.
1091  * \param restore_mdt_index  On restore: MDT index where to create the volatile
1092  *                           file. Use -1 for default.
1093  * \param restore_open_flags On restore: volatile file creation mode. Use
1094  *                           O_LOV_DELAY_CREATE to manually set the LOVEA
1095  *                           afterwards.
1096  * \param is_error           Whether this call is just to report an error.
1097  *
1098  * \return 0 on success.
1099  */
1100 int llapi_hsm_action_begin(struct hsm_copyaction_private **phcp,
1101                            const struct hsm_copytool_private *ct,
1102                            const struct hsm_action_item *hai,
1103                            int restore_mdt_index, int restore_open_flags,
1104                            bool is_error)
1105 {
1106         struct hsm_copyaction_private *hcp;
1107         int fd;
1108         int rc;
1109
1110         hcp = calloc(1, sizeof(*hcp));
1111         if (hcp == NULL)
1112                 return -ENOMEM;
1113
1114         hcp->source_fd = -1;
1115         hcp->data_fd = -1;
1116         hcp->ct_priv = ct;
1117         hcp->copy.hc_hai = *hai;
1118         hcp->copy.hc_hai.hai_len = sizeof(*hai);
1119
1120         if (is_error)
1121                 goto ok_out;
1122
1123         if (hai->hai_action == HSMA_ARCHIVE) {
1124                 fd = ct_open_by_fid(hcp->ct_priv, &hai->hai_dfid,
1125                                 O_RDONLY | O_NOATIME | O_NOFOLLOW | O_NONBLOCK);
1126                 if (fd < 0) {
1127                         rc = fd;
1128                         goto err_out;
1129                 }
1130
1131                 hcp->source_fd = fd;
1132         } else if (hai->hai_action == HSMA_RESTORE) {
1133                 rc = ct_md_getattr(hcp->ct_priv, &hai->hai_fid, &hcp->stat);
1134                 if (rc < 0)
1135                         goto err_out;
1136
1137                 rc = create_restore_volatile(hcp, restore_mdt_index,
1138                                              restore_open_flags);
1139                 if (rc < 0)
1140                         goto err_out;
1141         } else if (hai->hai_action == HSMA_REMOVE) {
1142                 /* Since remove is atomic there is no need to send an
1143                  * initial MDS_HSM_PROGRESS RPC. */
1144                 goto out_log;
1145         }
1146
1147         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_COPY_START, &hcp->copy);
1148         if (rc < 0) {
1149                 rc = -errno;
1150                 goto err_out;
1151         }
1152
1153 out_log:
1154         llapi_hsm_log_ct_progress(&hcp, hai, CT_START, 0, 0);
1155
1156 ok_out:
1157         hcp->magic = CP_PRIV_MAGIC;
1158         *phcp = hcp;
1159         return 0;
1160
1161 err_out:
1162         if (!(hcp->source_fd < 0))
1163                 close(hcp->source_fd);
1164
1165         if (!(hcp->data_fd < 0))
1166                 close(hcp->data_fd);
1167
1168         free(hcp);
1169
1170         return rc;
1171 }
1172
1173 /** Terminate an HSM action processing.
1174  * Should be called by copytools just having finished handling the request.
1175  * \param hdl[in,out]  Handle returned by llapi_hsm_action_start.
1176  * \param he[in]       The final range of copied data (for copy actions).
1177  * \param errval[in]   The status code of the operation.
1178  * \param flags[in]    The flags about the termination status (HP_FLAG_RETRY if
1179  *                     the error is retryable).
1180  *
1181  * \return 0 on success.
1182  */
1183 int llapi_hsm_action_end(struct hsm_copyaction_private **phcp,
1184                          const struct hsm_extent *he, int hp_flags, int errval)
1185 {
1186         struct hsm_copyaction_private   *hcp;
1187         struct hsm_action_item          *hai;
1188         int                              rc;
1189
1190         if (phcp == NULL || *phcp == NULL || he == NULL)
1191                 return -EINVAL;
1192
1193         hcp = *phcp;
1194
1195         if (hcp->magic != CP_PRIV_MAGIC)
1196                 return -EINVAL;
1197
1198         hai = &hcp->copy.hc_hai;
1199
1200         if (hai->hai_action == HSMA_RESTORE && errval == 0) {
1201                 struct ll_futimes_3 lfu = {
1202                         .lfu_atime_sec = hcp->stat.st_atim.tv_sec,
1203                         .lfu_atime_nsec = hcp->stat.st_atim.tv_nsec,
1204                         .lfu_mtime_sec = hcp->stat.st_mtim.tv_sec,
1205                         .lfu_mtime_nsec = hcp->stat.st_mtim.tv_nsec,
1206                         .lfu_ctime_sec = hcp->stat.st_ctim.tv_sec,
1207                         .lfu_ctime_nsec = hcp->stat.st_ctim.tv_nsec,
1208                 };
1209
1210                 rc = fsync(hcp->data_fd);
1211                 if (rc < 0) {
1212                         errval = -errno;
1213                         goto end;
1214                 }
1215
1216                 /* Set {a,m,c}time of volatile file to that of original. */
1217                 rc = ioctl(hcp->data_fd, LL_IOC_FUTIMES_3, &lfu);
1218                 if (rc < 0) {
1219                         errval = -errno;
1220                         goto end;
1221                 }
1222         }
1223
1224 end:
1225         /* In some cases, like restore, 2 FIDs are used.
1226          * Set the right FID to use here. */
1227         if (hai->hai_action == HSMA_ARCHIVE || hai->hai_action == HSMA_RESTORE)
1228                 hai->hai_fid = hai->hai_dfid;
1229
1230         /* Fill the last missing data that will be needed by
1231          * kernel to send a hsm_progress. */
1232         hcp->copy.hc_flags  = hp_flags;
1233         hcp->copy.hc_errval = abs(errval);
1234
1235         hcp->copy.hc_hai.hai_extent = *he;
1236
1237         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_COPY_END, &hcp->copy);
1238         if (rc) {
1239                 rc = -errno;
1240                 goto err_cleanup;
1241         }
1242
1243         llapi_hsm_log_ct_progress(&hcp, hai, CT_FINISH, 0, 0);
1244
1245 err_cleanup:
1246         if (!(hcp->source_fd < 0))
1247                 close(hcp->source_fd);
1248
1249         if (!(hcp->data_fd < 0))
1250                 close(hcp->data_fd);
1251
1252         free(hcp);
1253         *phcp = NULL;
1254
1255         return rc;
1256 }
1257
1258 /** Notify a progress in processing an HSM action.
1259  * \param hdl[in,out]   handle returned by llapi_hsm_action_start.
1260  * \param he[in]        the range of copied data (for copy actions).
1261  * \param total[in]     the expected total of copied data (for copy actions).
1262  * \param hp_flags[in]  HSM progress flags.
1263  * \return 0 on success.
1264  */
1265 int llapi_hsm_action_progress(struct hsm_copyaction_private *hcp,
1266                               const struct hsm_extent *he, __u64 total,
1267                               int hp_flags)
1268 {
1269         int                      rc;
1270         struct hsm_progress      hp;
1271         struct hsm_action_item  *hai;
1272
1273         if (hcp == NULL || he == NULL)
1274                 return -EINVAL;
1275
1276         if (hcp->magic != CP_PRIV_MAGIC)
1277                 return -EINVAL;
1278
1279         hai = &hcp->copy.hc_hai;
1280
1281         memset(&hp, 0, sizeof(hp));
1282
1283         hp.hp_cookie = hai->hai_cookie;
1284         hp.hp_flags  = hp_flags;
1285
1286         /* Progress is made on the data fid */
1287         hp.hp_fid = hai->hai_dfid;
1288         hp.hp_extent = *he;
1289
1290         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_PROGRESS, &hp);
1291         if (rc < 0)
1292                 rc = -errno;
1293
1294         llapi_hsm_log_ct_progress(&hcp, hai, CT_RUNNING, total, he->length);
1295
1296         return rc;
1297 }
1298
1299 /** Get the fid of object to be used for copying data.
1300  * @return error code if the action is not a copy operation.
1301  */
1302 int llapi_hsm_action_get_dfid(const struct hsm_copyaction_private *hcp,
1303                               struct lu_fid *fid)
1304 {
1305         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1306
1307         if (hcp->magic != CP_PRIV_MAGIC)
1308                 return -EINVAL;
1309
1310         if (hai->hai_action != HSMA_RESTORE && hai->hai_action != HSMA_ARCHIVE)
1311                 return -EINVAL;
1312
1313         *fid = hai->hai_dfid;
1314
1315         return 0;
1316 }
1317
1318 /**
1319  * Get a file descriptor to be used for copying data. It's up to the
1320  * caller to close the FDs obtained from this function.
1321  *
1322  * @retval a file descriptor on success.
1323  * @retval a negative error code on failure.
1324  */
1325 int llapi_hsm_action_get_fd(const struct hsm_copyaction_private *hcp)
1326 {
1327         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1328         int fd;
1329
1330         if (hcp->magic != CP_PRIV_MAGIC)
1331                 return -EINVAL;
1332
1333         if (hai->hai_action == HSMA_ARCHIVE) {
1334                 fd = dup(hcp->source_fd);
1335                 return fd < 0 ? -errno : fd;
1336         } else if (hai->hai_action == HSMA_RESTORE) {
1337                 fd = dup(hcp->data_fd);
1338                 return fd < 0 ? -errno : fd;
1339         } else {
1340                 return -EINVAL;
1341         }
1342 }
1343
1344 /**
1345  * Import an existing hsm-archived file into Lustre.
1346  *
1347  * Caller must access file by (returned) newfid value from now on.
1348  *
1349  * \param dst      path to Lustre destination (e.g. /mnt/lustre/my/file).
1350  * \param archive  archive number.
1351  * \param st       struct stat buffer containing file ownership, perm, etc.
1352  * \param stripe_* Striping options.  Currently ignored, since the restore
1353  *                 operation will set the striping.  In V2, this striping might
1354  *                 be used.
1355  * \param newfid[out] Filled with new Lustre fid.
1356  */
1357 int llapi_hsm_import(const char *dst, int archive, const struct stat *st,
1358                      unsigned long long stripe_size, int stripe_offset,
1359                      int stripe_count, int stripe_pattern, char *pool_name,
1360                      struct lu_fid *newfid)
1361 {
1362         struct hsm_user_import   hui;
1363         int                      fd;
1364         int                      rc = 0;
1365
1366         if (stripe_pattern == 0)
1367                 stripe_pattern = LOV_PATTERN_RAID0;
1368
1369         /* Create a non-striped file */
1370         fd = llapi_file_open_pool(dst, O_CREAT | O_WRONLY, st->st_mode,
1371                                   stripe_size, stripe_offset, stripe_count,
1372                                   stripe_pattern | LOV_PATTERN_F_RELEASED,
1373                                   pool_name);
1374         if (fd < 0) {
1375                 llapi_error(LLAPI_MSG_ERROR, fd,
1376                             "cannot create '%s' for import", dst);
1377                 return fd;
1378         }
1379
1380         /* Get the new fid in Lustre. Caller needs to use this fid
1381            from now on. */
1382         rc = llapi_fd2fid(fd, newfid);
1383         if (rc != 0) {
1384                 llapi_error(LLAPI_MSG_ERROR, rc,
1385                             "cannot get fid of '%s' for import", dst);
1386                 goto out_unlink;
1387         }
1388
1389         hui.hui_uid = st->st_uid;
1390         hui.hui_gid = st->st_gid;
1391         hui.hui_mode = st->st_mode;
1392         hui.hui_size = st->st_size;
1393         hui.hui_archive_id = archive;
1394         hui.hui_atime = st->st_atime;
1395         hui.hui_atime_ns = st->st_atim.tv_nsec;
1396         hui.hui_mtime = st->st_mtime;
1397         hui.hui_mtime_ns = st->st_mtim.tv_nsec;
1398         rc = ioctl(fd, LL_IOC_HSM_IMPORT, &hui);
1399         if (rc != 0) {
1400                 rc = -errno;
1401                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot import '%s'", dst);
1402                 goto out_unlink;
1403         }
1404
1405 out_unlink:
1406         if (fd >= 0)
1407                 close(fd);
1408         if (rc)
1409                 unlink(dst);
1410         return rc;
1411 }
1412
1413 /**
1414  * Return the current HSM states and HSM requests related to file pointed by \a
1415  * path.
1416  *
1417  * \param hus  Should be allocated by caller. Will be filled with current file
1418  *             states.
1419  *
1420  * \retval 0 on success.
1421  * \retval -errno on error.
1422  */
1423 int llapi_hsm_state_get_fd(int fd, struct hsm_user_state *hus)
1424 {
1425         int rc;
1426
1427         rc = ioctl(fd, LL_IOC_HSM_STATE_GET, hus);
1428         /* If error, save errno value */
1429         rc = rc ? -errno : 0;
1430
1431         return rc;
1432 }
1433
1434 /**
1435  * Return the current HSM states and HSM requests related to file pointed by \a
1436  * path.
1437  *
1438  * see llapi_hsm_state_get_fd() for args use and return
1439  */
1440 int llapi_hsm_state_get(const char *path, struct hsm_user_state *hus)
1441 {
1442         int fd;
1443         int rc;
1444
1445         fd = open(path, O_RDONLY | O_NONBLOCK);
1446         if (fd < 0)
1447                 return -errno;
1448
1449         rc = llapi_hsm_state_get_fd(fd, hus);
1450
1451         close(fd);
1452         return rc;
1453 }
1454
1455 /**
1456  * Set HSM states of file pointed by \a fd
1457  *
1458  * Using the provided bitmasks, the current HSM states for this file will be
1459  * changed. \a archive_id could be used to change the archive number also. Set
1460  * it to 0 if you do not want to change it.
1461  *
1462  * \param setmask      Bitmask for flag to be set.
1463  * \param clearmask    Bitmask for flag to be cleared.
1464  * \param archive_id  Archive number identifier to use. 0 means no change.
1465  *
1466  * \retval 0 on success.
1467  * \retval -errno on error.
1468  */
1469 int llapi_hsm_state_set_fd(int fd, __u64 setmask, __u64 clearmask,
1470                            __u32 archive_id)
1471 {
1472         struct hsm_state_set     hss;
1473         int                      rc;
1474
1475         hss.hss_valid = HSS_SETMASK|HSS_CLEARMASK;
1476         hss.hss_setmask = setmask;
1477         hss.hss_clearmask = clearmask;
1478         /* Change archive_id if provided. We can only change
1479          * to set something different than 0. */
1480         if (archive_id > 0) {
1481                 hss.hss_valid |= HSS_ARCHIVE_ID;
1482                 hss.hss_archive_id = archive_id;
1483         }
1484         rc = ioctl(fd, LL_IOC_HSM_STATE_SET, &hss);
1485         /* If error, save errno value */
1486         rc = rc ? -errno : 0;
1487
1488         return rc;
1489 }
1490
1491 /**
1492  * Set HSM states of file pointed by \a path.
1493  *
1494  * see llapi_hsm_state_set_fd() for args use and return
1495  */
1496 int llapi_hsm_state_set(const char *path, __u64 setmask, __u64 clearmask,
1497                         __u32 archive_id)
1498 {
1499         int fd;
1500         int rc;
1501
1502         fd = open(path, O_WRONLY | O_LOV_DELAY_CREATE | O_NONBLOCK);
1503         if (fd < 0)
1504                 return -errno;
1505
1506         rc = llapi_hsm_state_set_fd(fd, setmask, clearmask, archive_id);
1507
1508         close(fd);
1509         return rc;
1510 }
1511
1512 /**
1513  * Return the current HSM request related to file pointed by \a path.
1514  *
1515  * \param hca  Should be allocated by caller. Will be filled with current file
1516  *             actions.
1517  *
1518  * \retval 0 on success.
1519  * \retval -errno on error.
1520  */
1521 int llapi_hsm_current_action(const char *path, struct hsm_current_action *hca)
1522 {
1523         int fd;
1524         int rc;
1525
1526         fd = open(path, O_RDONLY | O_NONBLOCK);
1527         if (fd < 0)
1528                 return -errno;
1529
1530         rc = ioctl(fd, LL_IOC_HSM_ACTION, hca);
1531         /* If error, save errno value */
1532         rc = rc ? -errno : 0;
1533
1534         close(fd);
1535         return rc;
1536 }
1537
1538 /**
1539  * Allocate a hsm_user_request with the specified carateristics.
1540  * This structure should be freed with free().
1541  *
1542  * \return an allocated structure on success, NULL otherwise.
1543  */
1544 struct hsm_user_request *llapi_hsm_user_request_alloc(int itemcount,
1545                                                       int data_len)
1546 {
1547         int len = 0;
1548
1549         len += sizeof(struct hsm_user_request);
1550         len += sizeof(struct hsm_user_item) * itemcount;
1551         len += data_len;
1552
1553         return (struct hsm_user_request *)malloc(len);
1554 }
1555
1556 /**
1557  * Send a HSM request to Lustre, described in \param request.
1558  *
1559  * \param path    Fullpath to the file to operate on.
1560  * \param request The request, allocated with llapi_hsm_user_request_alloc().
1561  *
1562  * \return 0 on success, an error code otherwise.
1563  */
1564 int llapi_hsm_request(const char *path, const struct hsm_user_request *request)
1565 {
1566         int rc;
1567         int fd;
1568
1569         rc = get_root_path(WANT_FD, NULL, &fd, (char *)path, -1);
1570         if (rc)
1571                 return rc;
1572
1573         rc = ioctl(fd, LL_IOC_HSM_REQUEST, request);
1574         /* If error, save errno value */
1575         rc = rc ? -errno : 0;
1576
1577         close(fd);
1578         return rc;
1579 }
1580