4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 * (C) Copyright 2012 Commissariat a l'energie atomique et aux energies
9 * Copyright (c) 2013, 2017, Intel Corporation.
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
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.
25 * lustre/utils/liblustreapi_hsm.c
27 * lustreapi library for hsm calls
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>
40 #include <sys/ioctl.h>
48 #include <sys/types.h>
51 #include <sys/syscall.h>
54 #ifdef HAVE_LINUX_UNISTD_H
55 #include <linux/unistd.h>
60 #include <linux/lnet/lnetctl.h>
61 #include <lustre/lustreapi.h>
62 #include "lustreapi_internal.h"
64 #define OPEN_BY_FID_PATH dot_lustre_name"/fid"
66 /****** HSM Copytool API ********/
67 #define CT_PRIV_MAGIC 0xC0BE2001
68 struct hsm_copytool_private {
74 struct lustre_kernelcomm *kuc;
77 #define CP_PRIV_MAGIC 0x19880429
78 struct hsm_copyaction_private {
82 const struct hsm_copytool_private *ct_priv;
87 enum ct_progress_type {
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,
116 /* initialized in llapi_hsm_register_event_fifo() */
117 static int llapi_hsm_event_fd = -1;
118 static bool created_hsm_event_fifo;
120 static inline const char *llapi_hsm_ct_ev2str(int type)
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";
158 llapi_err_noerrno(LLAPI_MSG_ERROR,
159 "Unknown event type: %d", type);
165 * Writes a JSON event to the monitor FIFO. Noop if no FIFO has been
168 * \param event A list of llapi_json_items comprising a
169 * single JSON-formatted event.
171 * \retval 0 on success.
172 * \retval -errno on error.
174 static int llapi_hsm_write_json_event(struct llapi_json_item_list **event)
177 char time_string[40];
178 char json_buf[PIPE_BUF];
180 time_t event_time = time(0);
181 struct tm time_components;
182 struct llapi_json_item_list *json_items;
184 /* Noop unless the event fd was initialized */
185 if (llapi_hsm_event_fd < 0)
188 if (event == NULL || *event == NULL)
193 localtime_r(&event_time, &time_components);
195 if (strftime(time_string, sizeof(time_string), "%Y-%m-%d %T %z",
196 &time_components) == 0) {
198 llapi_error(LLAPI_MSG_ERROR, rc, "strftime() failed");
202 rc = llapi_json_add_item(&json_items, "event_time", LLAPI_JSON_STRING,
205 llapi_error(LLAPI_MSG_ERROR, -rc, "error in "
206 "llapi_json_add_item()");
210 buf_file = fmemopen(json_buf, sizeof(json_buf), "w");
211 if (buf_file == NULL)
214 rc = llapi_json_write_list(event, buf_file);
222 if (write(llapi_hsm_event_fd, json_buf, strlen(json_buf)) < 0) {
223 /* Ignore write failures due to missing reader. */
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.
236 * \param priv Opaque private control structure.
237 * \param event_type The type of event (register or unregister).
239 * \retval 0 on success.
240 * \retval -errno on error.
242 static int llapi_hsm_log_ct_registration(struct hsm_copytool_private **priv,
246 char agent_uuid[UUID_MAX];
247 struct hsm_copytool_private *ct;
248 struct llapi_json_item_list *json_items;
250 /* Noop unless the event fd was initialized */
251 if (llapi_hsm_event_fd < 0)
254 if (priv == NULL || *priv == NULL)
258 if (ct->magic != CT_PRIV_MAGIC)
261 if (event_type != CT_REGISTER && event_type != CT_UNREGISTER)
264 rc = llapi_json_init_list(&json_items);
268 rc = llapi_get_agent_uuid(ct->mnt, agent_uuid, sizeof(agent_uuid));
271 llapi_chomp_string(agent_uuid);
273 rc = llapi_json_add_item(&json_items, "uuid", LLAPI_JSON_STRING,
278 rc = llapi_json_add_item(&json_items, "mount_point", LLAPI_JSON_STRING,
283 rc = llapi_json_add_item(&json_items, "archive", LLAPI_JSON_INTEGER,
284 &ct->kuc->lk_data_count);
288 rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
289 (char *)llapi_hsm_ct_ev2str(event_type));
293 rc = llapi_hsm_write_json_event(&json_items);
300 llapi_error(LLAPI_MSG_ERROR, rc, "error in "
301 "llapi_hsm_log_ct_registration()");
304 if (json_items != NULL)
305 llapi_json_destroy_list(&json_items);
311 * Given a copytool progress update, construct a JSON event suitable for
312 * consumption by a copytool monitoring process.
314 * Examples of various events generated here and written by
315 * llapi_hsm_write_json_event:
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"}
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"}
337 * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "LOGGED_MESSAGE",
339 * "message": "lhsmtool_posix[42]: copytool fs=lustre archive#=2 item_count=1"}
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.
348 * \retval 0 on success.
349 * \retval -errno on error.
351 static int llapi_hsm_log_ct_progress(struct hsm_copyaction_private **phcp,
352 const struct hsm_action_item *hai,
354 __u64 total, __u64 current)
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;
364 /* Noop unless the event fd was initialized */
365 if (llapi_hsm_event_fd < 0)
368 if (phcp == NULL || *phcp == NULL)
373 rc = llapi_json_init_list(&json_items);
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);
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);
389 if (hcp->copy.hc_errval == ECANCELED) {
390 progress_type = CT_CANCEL;
394 if (hcp->copy.hc_errval != 0) {
395 progress_type = CT_ERROR;
397 rc = llapi_json_add_item(&json_items, "errno",
399 &hcp->copy.hc_errval);
403 rc = llapi_json_add_item(&json_items, "error",
405 strerror(hcp->copy.hc_errval));
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);
420 rc = llapi_json_add_item(&json_items, "lustre_path",
421 LLAPI_JSON_STRING, lustre_path);
425 rc = llapi_json_add_item(&json_items, "total_bytes",
426 LLAPI_JSON_BIGNUM, &total);
431 if (progress_type == CT_RUNNING) {
432 rc = llapi_json_add_item(&json_items, "current_bytes",
433 LLAPI_JSON_BIGNUM, ¤t);
439 rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
440 (char *)llapi_hsm_ct_ev2str(hai->hai_action +
445 rc = llapi_hsm_write_json_event(&json_items);
452 llapi_error(LLAPI_MSG_ERROR, rc, "error in "
453 "llapi_hsm_log_ct_progress()");
456 if (json_items != NULL)
457 llapi_json_destroy_list(&json_items);
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
468 * \param path Path to monitor FIFO.
470 * \retval 0 on success.
471 * \retval -errno on error.
473 int llapi_hsm_register_event_fifo(const char *path)
477 struct sigaction ignore_action;
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);
485 if (errno == EEXIST) {
486 if (stat(path, &statbuf) < 0) {
487 llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed",
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);
498 created_hsm_event_fifo = true;
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);
505 llapi_error(LLAPI_MSG_ERROR, errno,
506 "cannot open(%s) for read", path);
510 /* Open the FIFO for writes, but don't block on waiting
512 llapi_hsm_event_fd = open(path, O_WRONLY | O_NONBLOCK);
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! */
520 if (llapi_hsm_event_fd < 0) {
521 llapi_error(LLAPI_MSG_ERROR, -rc,
522 "cannot open(%s) for write", path);
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);
536 * Given a path to a FIFO, close its filehandle and delete the FIFO.
538 * \param path Path to monitor FIFO.
540 * \retval 0 on success.
541 * \retval -errno on error.
543 int llapi_hsm_unregister_event_fifo(const char *path)
545 /* Noop unless the event fd was initialized */
546 if (llapi_hsm_event_fd < 0)
549 if (close(llapi_hsm_event_fd) < 0)
552 if (created_hsm_event_fifo) {
554 created_hsm_event_fifo = false;
557 llapi_hsm_event_fd = -1;
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.
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.
574 void llapi_hsm_log_error(enum llapi_message_level level, int _rc,
575 const char *fmt, va_list args)
582 struct llapi_json_item_list *json_items;
584 /* Noop unless the event fd was initialized */
585 if (llapi_hsm_event_fd < 0)
588 rc = llapi_json_init_list(&json_items);
592 if ((level & LLAPI_MSG_NO_ERRNO) == 0) {
593 rc = llapi_json_add_item(&json_items, "errno",
599 rc = llapi_json_add_item(&json_items, "error",
606 va_copy(args2, args);
607 msg_len = vsnprintf(NULL, 0, fmt, args2) + 1;
610 msg = (char *) alloca(msg_len);
616 rc = vsnprintf(msg, msg_len, fmt, args);
620 rc = llapi_json_add_item(&json_items, "message",
626 rc = llapi_json_add_item(&json_items, "message",
628 "INTERNAL ERROR: message failed");
633 real_level = level & LLAPI_MSG_NO_ERRNO;
634 real_level = real_level > 0 ? level - LLAPI_MSG_NO_ERRNO : level;
636 rc = llapi_json_add_item(&json_items, "level", LLAPI_JSON_STRING,
637 (void *)llapi_msg_level2str(real_level));
641 rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
646 rc = llapi_hsm_write_json_event(&json_items);
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);
658 if (json_items != NULL)
659 llapi_json_destroy_list(&json_items);
662 /** Register a copytool
663 * \param[out] priv Opaque private control structure
664 * \param mnt Lustre filesystem mount point
665 * \param archive_count Number of valid archive IDs in \a archives
666 * \param archives Which archive numbers this copytool is
668 * \param rfd_flags flags applied to read fd of pipe
671 * \retval 0 on success.
672 * \retval -errno on error.
674 int llapi_hsm_copytool_register(struct hsm_copytool_private **priv,
675 const char *mnt, int archive_count,
676 int *archives, int rfd_flags)
678 struct hsm_copytool_private *ct;
681 if (archive_count > 0 && archives == NULL) {
682 llapi_err_noerrno(LLAPI_MSG_ERROR,
683 "NULL archive numbers");
687 for (rc = 0; rc < archive_count; rc++) {
688 /* in the list we have an all archive wildcard
689 * so move to all archives mode
691 if (archives[rc] == 0) {
697 ct = calloc(1, sizeof(*ct));
701 ct->magic = CT_PRIV_MAGIC;
703 ct->open_by_fid_fd = -1;
705 ct->mnt = strdup(mnt);
706 if (ct->mnt == NULL) {
711 ct->kuch = calloc(1, HAL_MAXSIZE + sizeof(*ct->kuch));
712 if (ct->kuch == NULL) {
717 ct->mnt_fd = open(ct->mnt, O_RDONLY);
718 if (ct->mnt_fd < 0) {
723 ct->open_by_fid_fd = openat(ct->mnt_fd, OPEN_BY_FID_PATH, O_RDONLY);
724 if (ct->open_by_fid_fd < 0) {
729 ct->kuc = malloc(sizeof(*ct) + archive_count * sizeof(__u32));
730 if (ct->kuc == NULL) {
735 ct->kuc->lk_rfd = LK_NOFD;
736 ct->kuc->lk_wfd = LK_NOFD;
738 rc = libcfs_ukuc_start(ct->kuc, KUC_GRP_HSM, rfd_flags);
742 ct->kuc->lk_flags = LK_FLG_DATANR;
743 ct->kuc->lk_data_count = archive_count;
744 for (rc = 0; rc < archive_count; rc++) {
745 if (archives[rc] < 0) {
746 llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when "
747 "archive id >= 0 is supported",
753 ct->kuc->lk_data[rc] = archives[rc];
756 rc = ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, ct->kuc);
759 llapi_error(LLAPI_MSG_ERROR, rc,
760 "cannot start copytool on '%s'", mnt);
764 llapi_hsm_log_ct_registration(&ct, CT_REGISTER);
766 /* Only the kernel reference keeps the write side open */
767 close(ct->kuc->lk_wfd);
768 ct->kuc->lk_wfd = LK_NOFD;
774 /* cleanup the kuc channel */
775 libcfs_ukuc_stop(ct->kuc);
781 if (!(ct->mnt_fd < 0))
784 if (!(ct->open_by_fid_fd < 0))
785 close(ct->open_by_fid_fd);
796 /** Deregister a copytool
797 * Note: under Linux, until llapi_hsm_copytool_unregister is called
798 * (or the program is killed), the libcfs module will be referenced
799 * and unremovable, even after Lustre services stop.
801 int llapi_hsm_copytool_unregister(struct hsm_copytool_private **priv)
803 struct hsm_copytool_private *ct;
805 if (priv == NULL || *priv == NULL)
809 if (ct->magic != CT_PRIV_MAGIC)
812 /* Close the read side of the KUC pipe. This should be done
813 * before unregistering to avoid deadlock: a ldlm_cb thread
814 * enters libcfs_kkuc_group_put() acquires kg_sem and blocks
815 * in pipe_write() due to full pipe; then we attempt to
816 * unregister and block on kg_sem. */
817 libcfs_ukuc_stop(ct->kuc);
819 /* Tell the kernel to stop sending us messages */
820 ct->kuc->lk_flags = LK_FLG_STOP;
821 ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, ct->kuc);
823 llapi_hsm_log_ct_registration(&ct, CT_UNREGISTER);
825 close(ct->open_by_fid_fd);
836 /** Returns a file descriptor to poll/select on.
837 * \param ct Opaque private control structure
838 * \retval -EINVAL on error
839 * \retval the file descriptor for reading HSM events from the kernel
841 int llapi_hsm_copytool_get_fd(struct hsm_copytool_private *ct)
843 if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
846 return libcfs_ukuc_get_rfd(ct->kuc);
849 /** Wait for the next hsm_action_list
850 * \param ct Opaque private control structure
851 * \param halh Action list handle, will be allocated here
852 * \param msgsize Number of bytes in the message, will be set here
853 * \return 0 valid message received; halh and msgsize are set
855 * Note: The application must not call llapi_hsm_copytool_recv until it has
856 * cleared the data in ct->kuch from the previous call.
858 int llapi_hsm_copytool_recv(struct hsm_copytool_private *ct,
859 struct hsm_action_list **halh, int *msgsize)
861 struct kuc_hdr *kuch;
862 struct hsm_action_list *hal;
865 if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
868 if (halh == NULL || msgsize == NULL)
874 rc = libcfs_ukuc_msg_get(ct->kuc, (char *)kuch,
875 HAL_MAXSIZE + sizeof(*kuch),
880 /* Handle generic messages */
881 if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
882 kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
887 if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
888 kuch->kuc_msgtype != HMT_ACTION_LIST) {
889 llapi_err_noerrno(LLAPI_MSG_ERROR,
890 "Unknown HSM message type %d:%d\n",
891 kuch->kuc_transport, kuch->kuc_msgtype);
896 if (kuch->kuc_msglen < sizeof(*kuch) + sizeof(*hal)) {
897 llapi_err_noerrno(LLAPI_MSG_ERROR, "Short HSM message %d",
903 /* Our message is a hsm_action_list. Use pointer math to skip
904 * kuch_hdr and point directly to the message payload.
906 hal = (struct hsm_action_list *)(kuch + 1);
908 /* Check that we have registered for this archive #
909 * if 0 registered, we serve any archive */
910 if (ct->kuc != NULL && ct->kuc->lk_data_count != 0) {
913 for (i = 0; i < ct->kuc->lk_data_count; i++) {
914 if (hal->hal_archive_id == ct->kuc->lk_data[i])
918 if (i >= ct->kuc->lk_data_count)
923 *msgsize = kuch->kuc_msglen - sizeof(*kuch);
932 /** Get parent path from mount point and fid.
934 * \param mnt Filesystem root path.
935 * \param fid Object FID.
936 * \param parent Destination buffer.
937 * \param parent_len Destination buffer size.
938 * \return 0 on success.
940 static int fid_parent(const char *mnt, const struct lu_fid *fid, char *parent,
945 long long recno = -1;
947 char strfid[FID_NOBRACE_LEN + 1];
950 snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(fid));
952 rc = llapi_fid2path(mnt, strfid, file, sizeof(file),
957 /* fid2path returns a relative path */
958 rc = snprintf(parent, parent_len, "%s/%s", mnt, file);
959 if (rc >= parent_len)
960 return -ENAMETOOLONG;
962 /* remove file name */
963 ptr = strrchr(parent, '/');
964 if (ptr == NULL || ptr == parent) {
974 static int ct_open_by_fid(const struct hsm_copytool_private *ct,
975 const struct lu_fid *fid, int open_flags)
977 char fid_name[FID_NOBRACE_LEN + 1];
980 snprintf(fid_name, sizeof(fid_name), DFID_NOBRACE, PFID(fid));
982 fd = openat(ct->open_by_fid_fd, fid_name, open_flags);
983 return fd < 0 ? -errno : fd;
987 * Get metadata attributes of file by FID.
989 * Use the IOC_MDC_GETFILEINFO ioctl (to send a MDS_GETATTR_NAME RPC)
990 * to get the attributes of the file identified by \a fid. This
991 * returns only the attributes stored on the MDT and avoids taking
992 * layout locks or accessing OST objects. It also bypasses the inode
993 * cache. Attributes are returned in \a st.
995 static int ct_md_getattr(const struct hsm_copytool_private *ct,
996 const struct lu_fid *fid,
999 struct lov_user_mds_data *lmd;
1000 char fname[FID_NOBRACE_LEN + 1] = "";
1004 rc = snprintf(fname, sizeof(fname), DFID_NOBRACE, PFID(fid));
1007 if (rc >= sizeof(fname) || rc == 0)
1010 lmd_size = offsetof(typeof(*lmd), lmd_lmm) +
1011 lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
1013 if (lmd_size < offsetof(typeof(*lmd), lmd_lmm) + XATTR_SIZE_MAX)
1014 lmd_size = offsetof(typeof(*lmd), lmd_lmm) + XATTR_SIZE_MAX;
1016 lmd = malloc(lmd_size);
1020 rc = get_lmd_info_fd(fname, ct->open_by_fid_fd, -1,
1021 lmd, lmd_size, GET_LMD_INFO);
1025 *stx = lmd->lmd_stx;
1032 /** Create the destination volatile file for a restore operation.
1034 * \param hcp Private copyaction handle.
1035 * \param mdt_index MDT index where to create the volatile file.
1036 * \param flags Volatile file creation flags.
1037 * \return 0 on success.
1039 static int create_restore_volatile(struct hsm_copyaction_private *hcp,
1040 int mdt_index, int open_flags)
1044 char parent[PATH_MAX + 1];
1045 const char *mnt = hcp->ct_priv->mnt;
1046 struct hsm_action_item *hai = &hcp->copy.hc_hai;
1048 rc = fid_parent(mnt, &hai->hai_fid, parent, sizeof(parent));
1050 /* fid_parent() failed, try to keep on going */
1051 llapi_error(LLAPI_MSG_ERROR, rc,
1052 "cannot get parent path to restore "DFID" "
1053 "using '%s'", PFID(&hai->hai_fid), mnt);
1054 snprintf(parent, sizeof(parent), "%s", mnt);
1057 fd = llapi_create_volatile_idx(parent, mdt_index, open_flags);
1061 rc = fchown(fd, hcp->statx.stx_uid, hcp->statx.stx_gid);
1065 rc = llapi_fd2fid(fd, &hai->hai_dfid);
1080 /** Start processing an HSM action.
1081 * Should be called by copytools just before starting handling a request.
1082 * It could be skipped if copytool only want to directly report an error,
1083 * \see llapi_hsm_action_end().
1085 * \param hcp Opaque action handle to be passed to
1086 * llapi_hsm_action_progress and llapi_hsm_action_end.
1087 * \param ct Copytool handle acquired at registration.
1088 * \param hai The hsm_action_item describing the request.
1089 * \param restore_mdt_index On restore: MDT index where to create the volatile
1090 * file. Use -1 for default.
1091 * \param restore_open_flags On restore: volatile file creation mode. Use
1092 * O_LOV_DELAY_CREATE to manually set the LOVEA
1094 * \param is_error Whether this call is just to report an error.
1096 * \return 0 on success.
1098 int llapi_hsm_action_begin(struct hsm_copyaction_private **phcp,
1099 const struct hsm_copytool_private *ct,
1100 const struct hsm_action_item *hai,
1101 int restore_mdt_index, int restore_open_flags,
1104 struct hsm_copyaction_private *hcp;
1108 hcp = calloc(1, sizeof(*hcp));
1112 hcp->source_fd = -1;
1115 hcp->copy.hc_hai = *hai;
1116 hcp->copy.hc_hai.hai_len = sizeof(*hai);
1121 if (hai->hai_action == HSMA_ARCHIVE) {
1122 fd = ct_open_by_fid(hcp->ct_priv, &hai->hai_dfid,
1123 O_RDONLY | O_NOATIME | O_NOFOLLOW | O_NONBLOCK);
1129 hcp->source_fd = fd;
1130 } else if (hai->hai_action == HSMA_RESTORE) {
1131 rc = ct_md_getattr(hcp->ct_priv, &hai->hai_fid, &hcp->statx);
1135 rc = create_restore_volatile(hcp, restore_mdt_index,
1136 restore_open_flags);
1139 } else if (hai->hai_action == HSMA_REMOVE) {
1140 /* Since remove is atomic there is no need to send an
1141 * initial MDS_HSM_PROGRESS RPC.
1142 * RW-PCC uses Lustre HSM mechanism for data synchronization.
1143 * At the beginning of RW-PCC attach, the client tries to
1144 * exclusively open the file by using a lease lock. A
1145 * successful lease open ensures that the current attach
1146 * process is the unique opener for the file.
1147 * After taking the lease, the file data is then copied from
1148 * OSTs into PCC and then the client closes the lease with
1149 * with a PCC attach intent.
1150 * However, for a file with HSM exists, archived state (i.e. a
1151 * cached file just was detached from PCC and restore into
1152 * OST), a HSM REMOVE request may delete the above PCC copy
1153 * during RW-PCC attach wrongly.
1154 * Thus, a open/close on the corresponding Lustre file is added
1155 * for HSMA_REMOVE here to solve this conflict.
1157 fd = ct_open_by_fid(hcp->ct_priv, &hai->hai_fid,
1158 O_RDONLY | O_NOATIME | O_NOFOLLOW | O_NONBLOCK);
1161 /* ignore the error in case of Remove Archive on Last
1164 if (rc == -ENOENT) {
1171 hcp->source_fd = fd;
1175 rc = ioctl(ct->mnt_fd, LL_IOC_HSM_COPY_START, &hcp->copy);
1182 llapi_hsm_log_ct_progress(&hcp, hai, CT_START, 0, 0);
1185 hcp->magic = CP_PRIV_MAGIC;
1190 if (!(hcp->source_fd < 0))
1191 close(hcp->source_fd);
1193 if (!(hcp->data_fd < 0))
1194 close(hcp->data_fd);
1201 /** Terminate an HSM action processing.
1202 * Should be called by copytools just having finished handling the request.
1203 * \param hdl[in,out] Handle returned by llapi_hsm_action_start.
1204 * \param he[in] The final range of copied data (for copy actions).
1205 * \param errval[in] The status code of the operation.
1206 * \param flags[in] The flags about the termination status (HP_FLAG_RETRY if
1207 * the error is retryable).
1209 * \return 0 on success.
1211 int llapi_hsm_action_end(struct hsm_copyaction_private **phcp,
1212 const struct hsm_extent *he, int hp_flags, int errval)
1214 struct hsm_copyaction_private *hcp;
1215 struct hsm_action_item *hai;
1218 if (phcp == NULL || *phcp == NULL || he == NULL)
1223 if (hcp->magic != CP_PRIV_MAGIC)
1226 hai = &hcp->copy.hc_hai;
1228 if (hai->hai_action == HSMA_RESTORE && errval == 0) {
1229 struct ll_futimes_3 lfu = {
1230 .lfu_atime_sec = hcp->statx.stx_atime.tv_sec,
1231 .lfu_atime_nsec = hcp->statx.stx_atime.tv_nsec,
1232 .lfu_mtime_sec = hcp->statx.stx_mtime.tv_sec,
1233 .lfu_mtime_nsec = hcp->statx.stx_mtime.tv_nsec,
1234 .lfu_ctime_sec = hcp->statx.stx_ctime.tv_sec,
1235 .lfu_ctime_nsec = hcp->statx.stx_ctime.tv_nsec,
1238 rc = fsync(hcp->data_fd);
1244 /* Set {a,m,c}time of volatile file to that of original. */
1245 rc = ioctl(hcp->data_fd, LL_IOC_FUTIMES_3, &lfu);
1253 /* In some cases, like restore, 2 FIDs are used.
1254 * Set the right FID to use here. */
1255 if (hai->hai_action == HSMA_ARCHIVE || hai->hai_action == HSMA_RESTORE)
1256 hai->hai_fid = hai->hai_dfid;
1258 /* Fill the last missing data that will be needed by
1259 * kernel to send a hsm_progress. */
1260 hcp->copy.hc_flags = hp_flags;
1261 hcp->copy.hc_errval = abs(errval);
1263 hcp->copy.hc_hai.hai_extent = *he;
1265 rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_COPY_END, &hcp->copy);
1271 llapi_hsm_log_ct_progress(&hcp, hai, CT_FINISH, 0, 0);
1274 if (!(hcp->source_fd < 0))
1275 close(hcp->source_fd);
1277 if (!(hcp->data_fd < 0))
1278 close(hcp->data_fd);
1286 /** Notify a progress in processing an HSM action.
1287 * \param hdl[in,out] handle returned by llapi_hsm_action_start.
1288 * \param he[in] the range of copied data (for copy actions).
1289 * \param total[in] the expected total of copied data (for copy actions).
1290 * \param hp_flags[in] HSM progress flags.
1291 * \return 0 on success.
1293 int llapi_hsm_action_progress(struct hsm_copyaction_private *hcp,
1294 const struct hsm_extent *he, __u64 total,
1298 struct hsm_progress hp;
1299 struct hsm_action_item *hai;
1301 if (hcp == NULL || he == NULL)
1304 if (hcp->magic != CP_PRIV_MAGIC)
1307 hai = &hcp->copy.hc_hai;
1309 memset(&hp, 0, sizeof(hp));
1311 hp.hp_cookie = hai->hai_cookie;
1312 hp.hp_flags = hp_flags;
1314 /* Progress is made on the data fid */
1315 hp.hp_fid = hai->hai_dfid;
1318 rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_PROGRESS, &hp);
1322 llapi_hsm_log_ct_progress(&hcp, hai, CT_RUNNING, total, he->length);
1327 /** Get the fid of object to be used for copying data.
1328 * @return error code if the action is not a copy operation.
1330 int llapi_hsm_action_get_dfid(const struct hsm_copyaction_private *hcp,
1333 const struct hsm_action_item *hai = &hcp->copy.hc_hai;
1335 if (hcp->magic != CP_PRIV_MAGIC)
1338 if (hai->hai_action != HSMA_RESTORE && hai->hai_action != HSMA_ARCHIVE)
1341 *fid = hai->hai_dfid;
1347 * Get a file descriptor to be used for copying data. It's up to the
1348 * caller to close the FDs obtained from this function.
1350 * @retval a file descriptor on success.
1351 * @retval a negative error code on failure.
1353 int llapi_hsm_action_get_fd(const struct hsm_copyaction_private *hcp)
1355 const struct hsm_action_item *hai = &hcp->copy.hc_hai;
1358 if (hcp->magic != CP_PRIV_MAGIC)
1361 if (hai->hai_action == HSMA_ARCHIVE) {
1362 fd = dup(hcp->source_fd);
1363 return fd < 0 ? -errno : fd;
1364 } else if (hai->hai_action == HSMA_RESTORE) {
1365 fd = dup(hcp->data_fd);
1366 return fd < 0 ? -errno : fd;
1373 * Import an existing hsm-archived file into Lustre.
1375 * Caller must access file by (returned) newfid value from now on.
1377 * \param dst path to Lustre destination (e.g. /mnt/lustre/my/file).
1378 * \param archive archive number.
1379 * \param st struct stat buffer containing file ownership, perm, etc.
1380 * \param stripe_* Striping options. Currently ignored, since the restore
1381 * operation will set the striping. In V2, this striping might
1383 * \param newfid[out] Filled with new Lustre fid.
1385 int llapi_hsm_import(const char *dst, int archive, const struct stat *st,
1386 unsigned long long stripe_size, int stripe_offset,
1387 int stripe_count, int stripe_pattern, char *pool_name,
1388 struct lu_fid *newfid)
1390 struct hsm_user_import hui;
1394 if (stripe_pattern == 0)
1395 stripe_pattern = LOV_PATTERN_RAID0;
1397 /* Create a non-striped file */
1398 fd = llapi_file_open_pool(dst, O_CREAT | O_WRONLY, st->st_mode,
1399 stripe_size, stripe_offset, stripe_count,
1400 stripe_pattern | LOV_PATTERN_F_RELEASED,
1403 llapi_error(LLAPI_MSG_ERROR, fd,
1404 "cannot create '%s' for import", dst);
1408 /* Get the new fid in Lustre. Caller needs to use this fid
1410 rc = llapi_fd2fid(fd, newfid);
1412 llapi_error(LLAPI_MSG_ERROR, rc,
1413 "cannot get fid of '%s' for import", dst);
1417 hui.hui_uid = st->st_uid;
1418 hui.hui_gid = st->st_gid;
1419 hui.hui_mode = st->st_mode;
1420 hui.hui_size = st->st_size;
1421 hui.hui_archive_id = archive;
1422 hui.hui_atime = st->st_atime;
1423 hui.hui_atime_ns = st->st_atim.tv_nsec;
1424 hui.hui_mtime = st->st_mtime;
1425 hui.hui_mtime_ns = st->st_mtim.tv_nsec;
1426 rc = ioctl(fd, LL_IOC_HSM_IMPORT, &hui);
1429 llapi_error(LLAPI_MSG_ERROR, rc, "cannot import '%s'", dst);
1442 * Return the current HSM states and HSM requests related to file pointed by \a
1445 * \param hus Should be allocated by caller. Will be filled with current file
1448 * \retval 0 on success.
1449 * \retval -errno on error.
1451 int llapi_hsm_state_get_fd(int fd, struct hsm_user_state *hus)
1455 rc = ioctl(fd, LL_IOC_HSM_STATE_GET, hus);
1456 /* If error, save errno value */
1457 rc = rc ? -errno : 0;
1463 * Return the current HSM states and HSM requests related to file pointed by \a
1466 * see llapi_hsm_state_get_fd() for args use and return
1468 int llapi_hsm_state_get(const char *path, struct hsm_user_state *hus)
1473 fd = open(path, O_RDONLY | O_NONBLOCK);
1477 rc = llapi_hsm_state_get_fd(fd, hus);
1484 * Set HSM states of file pointed by \a fd
1486 * Using the provided bitmasks, the current HSM states for this file will be
1487 * changed. \a archive_id could be used to change the archive number also. Set
1488 * it to 0 if you do not want to change it.
1490 * \param setmask Bitmask for flag to be set.
1491 * \param clearmask Bitmask for flag to be cleared.
1492 * \param archive_id Archive number identifier to use. 0 means no change.
1494 * \retval 0 on success.
1495 * \retval -errno on error.
1497 int llapi_hsm_state_set_fd(int fd, __u64 setmask, __u64 clearmask,
1500 struct hsm_state_set hss;
1503 hss.hss_valid = HSS_SETMASK|HSS_CLEARMASK;
1504 hss.hss_setmask = setmask;
1505 hss.hss_clearmask = clearmask;
1506 /* Change archive_id if provided. We can only change
1507 * to set something different than 0. */
1508 if (archive_id > 0) {
1509 hss.hss_valid |= HSS_ARCHIVE_ID;
1510 hss.hss_archive_id = archive_id;
1512 rc = ioctl(fd, LL_IOC_HSM_STATE_SET, &hss);
1513 /* If error, save errno value */
1514 rc = rc ? -errno : 0;
1520 * Set HSM states of file pointed by \a path.
1522 * see llapi_hsm_state_set_fd() for args use and return
1524 int llapi_hsm_state_set(const char *path, __u64 setmask, __u64 clearmask,
1530 fd = open(path, O_WRONLY | O_LOV_DELAY_CREATE | O_NONBLOCK);
1534 rc = llapi_hsm_state_set_fd(fd, setmask, clearmask, archive_id);
1541 * Return the current HSM request related to file pointed by \a path.
1543 * \param hca Should be allocated by caller. Will be filled with current file
1546 * \retval 0 on success.
1547 * \retval -errno on error.
1549 int llapi_hsm_current_action(const char *path, struct hsm_current_action *hca)
1554 fd = open(path, O_RDONLY | O_NONBLOCK);
1558 rc = ioctl(fd, LL_IOC_HSM_ACTION, hca);
1559 /* If error, save errno value */
1560 rc = rc ? -errno : 0;
1567 * Allocate a hsm_user_request with the specified carateristics.
1568 * This structure should be freed with free().
1570 * \return an allocated structure on success, NULL otherwise.
1572 struct hsm_user_request *llapi_hsm_user_request_alloc(int itemcount,
1577 len += sizeof(struct hsm_user_request);
1578 len += sizeof(struct hsm_user_item) * itemcount;
1581 return (struct hsm_user_request *)malloc(len);
1585 * Send a HSM request to Lustre, described in \param request.
1587 * \param path Fullpath to the file to operate on.
1588 * \param request The request, allocated with llapi_hsm_user_request_alloc().
1590 * \return 0 on success, an error code otherwise.
1592 int llapi_hsm_request(const char *path, const struct hsm_user_request *request)
1597 rc = get_root_path(WANT_FD, NULL, &fd, (char *)path, -1);
1601 rc = ioctl(fd, LL_IOC_HSM_REQUEST, request);
1602 /* If error, save errno value */
1603 rc = rc ? -errno : 0;