Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / common / module.c
1 /*
2  * Ceph - scalable distributed file system
3  *
4  * Copyright (C) 2014 Inktank Storage, Inc.
5  *
6  * This is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License version 2.1, as published by the Free Software
9  * Foundation.  See file COPYING.
10  *
11  */
12
13 #include "acconfig.h"
14 #include <errno.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #if defined(__FreeBSD__)
19 #include <sys/wait.h>
20 #endif 
21
22 /*
23  * TODO: Switch to libkmod when we abandon older platforms.  The APIs
24  * we want are:
25  *
26  * - kmod_module_new_from_name() for obtaining handles;
27  * - kmod_module_probe_insert_module() for module_load();
28  * - kmod_module_get_info(), kmod_module_info_get_{key,value}() for
29  *   module_has_param().
30  */
31
32 /*
33  * Return command's exit status or -1 on error.
34  */
35 static int run_command(const char *command)
36 {
37         int status;
38
39         status = system(command);
40         if (status >= 0 && WIFEXITED(status))
41                 return WEXITSTATUS(status);
42
43         if (status < 0) {
44                 char error_buf[80];
45 #ifdef STRERROR_R_CHAR_P
46                 char* dummy = strerror_r(errno, error_buf, sizeof(error_buf));
47                 (void)dummy;
48 #else
49                 strerror_r(errno, error_buf, sizeof(error_buf));
50 #endif
51                 fprintf(stderr, "couldn't run '%s': %s\n", command,
52                         error_buf);
53         } else if (WIFSIGNALED(status)) {
54                 fprintf(stderr, "'%s' killed by signal %d\n", command,
55                         WTERMSIG(status));
56         } else {
57                 fprintf(stderr, "weird status from '%s': %d\n", command,
58                         status);
59         }
60
61         return -1;
62 }
63
64 int module_has_param(const char *module, const char *param)
65 {
66         char command[128];
67
68         snprintf(command, sizeof(command),
69                  "/sbin/modinfo -F parm %s | /bin/grep -q ^%s:",
70                  module, param);
71
72         return run_command(command) == 0;
73 }
74
75 int module_load(const char *module, const char *options)
76 {
77         char command[128];
78
79         snprintf(command, sizeof(command), "/sbin/modprobe %s %s",
80                  module, (options ? options : ""));
81
82         return run_command(command);
83 }