Whamcloud - gitweb
LU-17744 ldiskfs: mballoc stats fixes
[fs/lustre-release.git] / lustre / utils / liblustreapi_util.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * (C) Copyright (c) 2015, Cray Inc, all rights reserved.
7  *
8  * Copyright (c) 2016, 2017, Intel Corporation.
9  *
10  * All rights reserved. This program and the accompanying materials
11  * are made available under the terms of the GNU Lesser General Public License
12  * LGPL version 2.1 or (at your discretion) any later version.
13  * LGPL version 2.1 accompanies this distribution, and is available at
14  * http://www.gnu.org/licenses/lgpl-2.1.html
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * LGPL HEADER END
22  */
23 /*
24  * lustre/utils/liblustreapi_util.c
25  *
26  * Misc LGPL-licenced utility functions for liblustreapi.
27  *
28  * Author: Frank Zago <fzago@cray.com>
29  */
30
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdbool.h>
34 #include <stddef.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <sys/ioctl.h>
38 #include <string.h>
39 #include <unistd.h>
40 #include <sys/time.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <sys/syscall.h>
44 #include <libgen.h> /* for dirname() */
45 #include <lustre/lustreapi.h>
46 #include <linux/lustre/lustre_ver.h>    /* only until LUSTRE_VERSION_CODE is gone */
47 #include "lustreapi_internal.h"
48
49 /*
50  * Indicate whether the liblustreapi_init() constructor below has run or not.
51  *
52  * This can be used by external programs to ensure that the initialization
53  * mechanism has actually worked.
54  */
55 bool liblustreapi_initialized;
56
57 /**
58  * Initialize the library once at startup.
59  *
60  * Initializes the random number generator (random()). Get
61  * data from different places in case one of them fails. This
62  * is enough to get reasonably random numbers, but is not
63  * strong enough to be used for cryptography.
64  */
65 static __attribute__ ((constructor)) void liblustreapi_init(void)
66 {
67         unsigned int    seed;
68         struct timeval  tv;
69         int             fd;
70
71         seed = syscall(SYS_gettid);
72
73         if (gettimeofday(&tv, NULL) == 0) {
74                 seed ^= tv.tv_sec;
75                 seed ^= tv.tv_usec;
76         }
77
78         fd = open("/dev/urandom", O_RDONLY | O_NOFOLLOW);
79         if (fd >= 0) {
80                 unsigned int rnumber;
81                 ssize_t ret;
82
83                 ret = read(fd, &rnumber, sizeof(rnumber));
84                 seed ^= rnumber ^ ret;
85                 close(fd);
86         }
87
88         srandom(seed);
89         liblustreapi_initialized = true;
90 }
91
92 /**
93  * Return the release version for the Lustre modules, e.g. 2.6.92.
94  *
95  * The "version" file in /proc currently returns only the line:
96  * lustre: 2.8.52
97  *
98  * but in the past it also returned more lines that should be ignored:
99  * kernel: patchless_client
100  * build: v2_6_92_0-gadb3ee4-2.6.32-431.29.2.el6_lustre.g36cd22b.x86_64
101  *
102  * \param version[in,out]       buffer to store build version string
103  * \param version_size[in]      size of \a version
104  *
105  * \retval                      0 on success
106  * \retval                      -1 on failure, errno set
107  */
108 int llapi_get_version_string(char *version, unsigned int version_size)
109 {
110         char buffer[4096];
111         char *ptr;
112         int rc;
113
114         if (version == NULL || version_size == 0) {
115                 errno = EINVAL;
116                 return -1;
117         }
118
119         rc = get_lustre_param_value(NULL, NULL, FILTER_BY_NONE, "version",
120                                     buffer, sizeof(buffer));
121         if (rc < 0) {
122                 errno = -rc;
123                 return -1;
124         }
125
126         ptr = strstr(buffer, "lustre:");
127         if (ptr) {
128                 ptr += strlen("lustre:");
129                 while (*ptr == ' ' || *ptr == '\t')
130                         ptr++;
131         } else {
132                 ptr = buffer;
133         }
134         llapi_chomp_string(ptr);
135
136         if (ptr[0] == '\0') {
137                 errno = ENODATA;
138                 return -1;
139         }
140
141         if (snprintf(version, version_size, "%s", ptr) >= version_size) {
142                 errno = EOVERFLOW;
143                 return -1;
144         }
145         return 0;
146 }
147
148 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 4, 53, 0)
149 /**
150  * Return the build version of the Lustre code.
151  *
152  * The **version argument is pointless, so llapi_get_version_string() is
153  * better to use in the future, but give users a few versions to fix * it.
154  *
155  * \param buffer[in]            temporary buffer to hold version string
156  * \param buffer_size[in]       length of the \a buffer
157  * \param version[out]          pointer to the start of build version string
158  *
159  * \retval                      0 on success
160  * \retval                      -ve errno on failure
161  */
162 int llapi_get_version(char *buffer, int buffer_size, char **version)
163 {
164         static bool printed;
165         int rc;
166
167         if (!printed) {
168                 fprintf(stderr,
169                         "%s deprecated, use llapi_get_version_string()\n",
170                         __func__);
171                 printed = true;
172         }
173
174         rc = llapi_get_version_string(buffer, buffer_size);
175         /* keep old return style for this legacy function */
176         if (rc == -1)
177                 rc = -errno;
178         else
179                 *version = buffer;
180
181         return rc;
182 }
183 #endif /* LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 4, 53, 0) */
184
185 /*
186  * fsname must be specified
187  * if poolname is NULL, search tgtname in fsname
188  * if poolname is not NULL:
189  *  if poolname not found returns errno < 0
190  *  if tgtname is NULL, returns 1 if pool is not empty and 0 if pool empty
191  *  if tgtname is not NULL, returns 1 if target is in pool and 0 if not
192  */
193 int llapi_search_tgt(const char *fsname, const char *poolname,
194                      const char *tgtname, bool is_mdt)
195 {
196         char buffer[PATH_MAX];
197         size_t len = 0;
198         glob_t param;
199         FILE *fd;
200         int rc;
201
202         if (fsname && fsname[0] == '\0')
203                 fsname = NULL;
204         if (!fsname) {
205                 rc = -EINVAL;
206                 goto out;
207         }
208
209         if (poolname && poolname[0] == '\0')
210                 poolname = NULL;
211         if (tgtname) {
212                 if (tgtname[0] == '\0')
213                         tgtname = NULL;
214                 else
215                         len = strlen(tgtname);
216         }
217
218         /* You need one or the other to have something in it */
219         if (!poolname && !tgtname) {
220                 rc = -EINVAL;
221                 goto out;
222         }
223
224         if (poolname) {
225                 rc = poolpath(&param, fsname, NULL);
226                 if (!rc) {
227                         snprintf(buffer, sizeof(buffer) - 1, "%s/%s",
228                                  param.gl_pathv[0], poolname);
229                         buffer[sizeof(buffer) - 1] = '\0';
230                 }
231         } else {
232                 rc = get_lustre_param_path(is_mdt ? "lmv" : "lov", fsname,
233                                            FILTER_BY_FS_NAME,
234                                            "target_obd", &param);
235                 if (!rc) {
236                         strncpy(buffer, param.gl_pathv[0],
237                                 sizeof(buffer) - 1);
238                         buffer[sizeof(buffer) - 1] = '\0';
239                 }
240         }
241         cfs_free_param_data(&param);
242         if (rc)
243                 goto out;
244
245         fd = fopen(buffer, "r");
246         if (!fd) {
247                 rc = -errno;
248                 goto out;
249         }
250
251         while (fgets(buffer, sizeof(buffer), fd)) {
252                 if (!poolname) {
253                         char *ptr;
254                         /* Search for an tgtname in the list of all targets
255                          * Line format is IDX: fsname-OST/MDTxxxx_UUID STATUS */
256                         ptr = strchr(buffer, ' ');
257                         if (ptr && strncmp(ptr + 1, tgtname, len) == 0) {
258                                 rc = 1;
259                                 goto out_close;
260                         }
261                 } else {
262                         /* Search for an tgtname in a pool,
263                          * (or an existing non-empty pool if no tgtname) */
264                         if (!tgtname || strncmp(buffer, tgtname, len) == 0) {
265                                 rc = 1;
266                                 goto out_close;
267                         }
268                 }
269         }
270 out_close:
271         fclose(fd);
272 out:
273         if (rc < 0)
274                 errno = -rc;
275         return rc;
276 }
277
278 int llapi_search_mdt(const char *fsname, const char *poolname,
279                      const char *mdtname)
280 {
281         return llapi_search_tgt(fsname, poolname, mdtname, true);
282 }
283
284 int llapi_search_ost(const char *fsname, const char *poolname,
285                      const char *ostname)
286 {
287         return llapi_search_tgt(fsname, poolname, ostname, false);
288 }
289
290 /**
291  * Return the open fd for a given device/path provided
292  *
293  * \param device[in]            buffer holding device or path string
294  * \param rootfd[out]           file descriptor after successful opening of
295  *                              of above path or device
296  *
297  * \retval                      0 on success
298  * \retval                      -ve on failure
299  */
300 int llapi_root_path_open(const char *device, int *rootfd)
301 {
302         int tmp_fd, rc;
303
304         if (*device == '/')
305                 rc = get_root_path(WANT_FD, NULL, &tmp_fd,
306                                    (char *)device, -1, NULL, NULL);
307         else
308                 rc = get_root_path(WANT_FD, (char *)device, &tmp_fd,
309                                    NULL, -1, NULL, NULL);
310
311         if (!rc)
312                 *rootfd = dup(tmp_fd);
313
314         return rc;
315 }
316
317 /**
318  * Call IOCTL to remove file by fid. The fd must be valid and fa
319  * (fid_array) struct must allready be populated.
320  *
321  * \param fd[in]                valid descriptor of device/path
322  * \param fa[in]                fid_array struct holding fids
323  *
324  * \retval                      0 on success
325  * \retval                      -ve/errno on failure
326  */
327 int llapi_rmfid_at(int fd, struct fid_array *fa)
328 {
329         return ioctl(fd, LL_IOC_RMFID, fa) ? -errno : 0;
330 }
331
332 int llapi_rmfid(const char *path, struct fid_array *fa)
333 {
334         int rootfd, rc;
335
336         rc = llapi_root_path_open(path, &rootfd);
337         if (rc < 0) {
338                 fprintf(stderr,
339                         "lfs rmfid: error opening device/fsname '%s': %s\n",
340                         path, strerror(-rc));
341                 return -rc;
342         }
343
344         rc = llapi_rmfid_at(rootfd, fa);
345         close(rootfd);
346         if (rc < 0) {
347                 fprintf(stderr, "lfs rmfid: cannot remove FIDs: %s\n",
348                         strerror(-rc));
349                 return rc;
350         }
351
352         return rc ? -errno : 0;
353 }
354
355 int llapi_direntry_remove(char *dname)
356 {
357 #ifdef LL_IOC_REMOVE_ENTRY
358         char *dirpath = NULL;
359         char *namepath = NULL;
360         char *dir;
361         char *filename;
362         int fd = -1;
363         int rc = 0;
364
365         dirpath = strdup(dname);
366         if (!dirpath)
367                 return -ENOMEM;
368
369         namepath = strdup(dname);
370         if (!namepath) {
371                 rc = -ENOMEM;
372                 goto out_dirpath;
373         }
374
375         filename = basename(namepath);
376
377         dir = dirname(dirpath);
378
379         fd = open(dir, O_DIRECTORY | O_RDONLY);
380         if (fd < 0) {
381                 rc = -errno;
382                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'",
383                             filename);
384                 goto out;
385         }
386
387         if (ioctl(fd, LL_IOC_REMOVE_ENTRY, filename))
388                 llapi_error(LLAPI_MSG_ERROR, errno,
389                             "error on ioctl %#lx for '%s' (%d)",
390                             (long)LL_IOC_LMV_SETSTRIPE, filename, fd);
391 out:
392         close(fd);
393         free(namepath);
394 out_dirpath:
395         free(dirpath);
396         return rc;
397 #else
398         return -EOPNOTSUPP;
399 #endif
400 }
401
402 int llapi_unlink_foreign(char *name)
403 {
404         int fd = -1;
405         int rc = 0;
406
407         fd = open(name, O_DIRECTORY | O_RDONLY | O_NOFOLLOW);
408         if (fd < 0 && errno != ENOTDIR) {
409                 rc = -errno;
410                 llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'", name);
411                 goto out;
412         } else if (errno == ENOTDIR) {
413                 fd = open(name, O_RDONLY | O_NOFOLLOW);
414                 if (fd < 0) {
415                         rc = -errno;
416                         llapi_error(LLAPI_MSG_ERROR, rc, "unable to open '%s'",
417                                     name);
418                         goto out;
419                 }
420         }
421
422         /* allow foreign symlink file/dir to be unlinked */
423         if (ioctl(fd, LL_IOC_UNLOCK_FOREIGN)) {
424                 llapi_error(LLAPI_MSG_ERROR, errno,
425                             "error on ioctl %#lx for '%s' (%d)",
426                             (long)LL_IOC_UNLOCK_FOREIGN, name, fd);
427                 rc = -errno;
428         }
429
430         /* XXX do not set AT_REMOVEDIR in flags even for a dir, as due to the
431          * hack for foreign symlink it will fail the directory check in
432          * Kernel's syscall code and return ENOTDIR, so treat all as files
433          */
434         rc = unlinkat(AT_FDCWD, name, 0);
435         if (rc == -1 && errno == EISDIR)
436                 rc = unlinkat(AT_FDCWD, name, AT_REMOVEDIR);
437
438         if (rc == -1) {
439                 llapi_error(LLAPI_MSG_ERROR, errno,
440                             "error on unlinkat for '%s' (%d)", name, fd);
441                 rc = -errno;
442         }
443
444 out:
445         if (fd != -1)
446                 close(fd);
447         return rc;
448 }
449
450 int llapi_get_fsname_instance(const char *path, char *fsname, size_t fsname_len,
451                               char *instance, size_t instance_len)
452 {
453         struct obd_uuid uuid_buf;
454         char *uuid = uuid_buf.uuid;
455         char *ptr;
456         int rc;
457
458         memset(&uuid_buf, 0, sizeof(uuid_buf));
459         rc = llapi_file_get_lov_uuid(path, &uuid_buf);
460         if (rc)
461                 return rc;
462
463         /*
464          * We want to turn fs-foo-clilov-ffff88002738bc00 into 'fs-foo' and
465          * 'ffff88002738bc00' in a portable way that doesn't depend on what is
466          * after "-clilov-" as it may change to a UUID string in the future.
467          * Unfortunately, the "fsname" part may contain a dash, so we can't
468          * just skip to the first dash, and if the "instance" is a UUID in the
469          * future we can't necessarily go to the last dash either.
470          */
471         ptr = strstr(uuid, "-clilov-");
472         if (!ptr || (!fsname && !instance)) {
473                 rc = -EINVAL;
474                 goto out;
475         }
476
477         *ptr = '\0';
478         ptr += strlen("-clilov-");
479         if (instance) {
480                 snprintf(instance, instance_len, "%s", ptr);
481                 if (strlen(ptr) >= instance_len)
482                         rc = -ENAMETOOLONG;
483         }
484
485         if (fsname) {
486                 snprintf(fsname, fsname_len, "%s", uuid);
487                 if (strlen(uuid) >= fsname_len)
488                         rc = -ENAMETOOLONG;
489         }
490
491 out:
492         errno = -rc;
493         return rc;
494 }
495
496 int llapi_getname(const char *path, char *name, size_t namelen)
497 {
498         char fsname[16];
499         char instance[40];
500         int rc;
501
502         rc = llapi_get_fsname_instance(path, fsname, sizeof(fsname),
503                                        instance, sizeof(instance));
504         if (rc)
505                 return rc;
506
507         snprintf(name, namelen, "%s-%s", fsname, instance);
508         if (strlen(fsname) + 1 + strlen(instance) >= namelen) {
509                 rc = -ENAMETOOLONG;
510                 errno = -rc;
511         }
512
513         return rc;
514 }
515
516 int llapi_get_instance(const char *path, char *instance, size_t instance_len)
517 {
518         return llapi_get_fsname_instance(path, NULL, 0, instance, instance_len);
519 }
520
521 int llapi_get_fsname(const char *path, char *fsname, size_t fsname_len)
522 {
523         return llapi_get_fsname_instance(path, fsname, fsname_len, NULL, 0);
524 }