be188feac7151f99dabdad628bb1daab99729f5f
[collectd.git] / src / gpu_nvml.c
1 /*
2 Copyright 2018 Evgeny Naumov
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "daemon/collectd.h"
24 #include "daemon/common.h"
25 #include "daemon/plugin.h"
26
27 #include <nvml.h>
28 #include <stdint.h>
29 #include <stdio.h>
30
31 #define MAX_DEVNAME_LEN 256
32 #define PLUGIN_NAME "gpu_nvml"
33
34 static nvmlReturn_t nv_status = NVML_SUCCESS;
35 static char *nv_errline = "";
36
37 #define TRY_CATCH(f, catch)                                                    \
38   if ((nv_status = f) != NVML_SUCCESS) {                                       \
39     nv_errline = #f;                                                           \
40     goto catch;                                                                \
41   }
42
43 #define TRY_CATCH_OPTIONAL(f, catch)                                           \
44   if ((nv_status = f) != NVML_SUCCESS &&                                       \
45       nv_status != NVML_ERROR_NOT_SUPPORTED) {                                 \
46     nv_errline = #f;                                                           \
47     goto catch;                                                                \
48   }
49
50 #define TRY(f) TRY_CATCH(f, catch)
51 #define TRYOPT(f) TRY_CATCH_OPTIONAL(f, catch)
52
53 #define KEY_GPUINDEX "GPUIndex"
54 #define KEY_IGNORESELECTED "IgnoreSelected"
55
56 static const char *config_keys[] = {
57     KEY_GPUINDEX, KEY_IGNORESELECTED,
58 };
59 static const unsigned int n_config_keys = STATIC_ARRAY_SIZE(config_keys);
60
61 // This is a bitflag, necessitating the (extremely conservative) assumption
62 // that there are no more than 64 GPUs on this system.
63 static uint64_t conf_match_mask = 0;
64 static bool conf_mask_is_exclude = 0;
65
66 static int nvml_config(const char *key, const char *value) {
67
68   if (strcasecmp(key, KEY_GPUINDEX) == 0) {
69     char *eptr;
70     unsigned long device_ix = strtoul(value, &eptr, 10);
71     if (eptr == value) {
72       ERROR(PLUGIN_NAME ": Failed to parse GPUIndex value \"%s\"", value);
73       return -1;
74     }
75     if (device_ix >= 64) {
76       ERROR(PLUGIN_NAME
77             ": At most 64 GPUs (0 <= GPUIndex < 64) are supported!");
78       return -2;
79     }
80     conf_match_mask |= (1 << device_ix);
81   } else if (strcasecmp(key, KEY_IGNORESELECTED)) {
82     conf_mask_is_exclude = IS_TRUE(value);
83   } else {
84     ERROR(PLUGIN_NAME ": Unrecognized config option %s", key);
85     return -10;
86   }
87
88   return 0;
89 }
90
91 static int nvml_init(void) {
92   TRY(nvmlInit());
93   return 0;
94
95   catch : ERROR(PLUGIN_NAME ": NVML init failed with %d", nv_status);
96   return -1;
97 }
98
99 static int nvml_shutdown(void) {
100   TRY(nvmlShutdown())
101   return 0;
102
103   catch : ERROR(PLUGIN_NAME ": NVML shutdown failed with %d", nv_status);
104   return -1;
105 }
106
107 static void nvml_submit_gauge(const char *plugin_instance, const char *type,
108                               const char *type_instance, gauge_t nvml) {
109
110   value_list_t vl = VALUE_LIST_INIT;
111
112   vl.values = &(value_t){.gauge = nvml};
113   vl.values_len = 1;
114
115   sstrncpy(vl.plugin, PLUGIN_NAME, sizeof(vl.plugin));
116   sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
117
118   sstrncpy(vl.type, type, sizeof(vl.type));
119
120   if (type_instance != NULL) {
121     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
122   }
123
124   plugin_dispatch_values(&vl);
125 }
126
127 static int nvml_read(void) {
128
129   unsigned int device_count;
130   TRY_CATCH(nvmlDeviceGetCount(&device_count), catch_nocount);
131
132   if (device_count > 64) {
133     device_count = 64;
134   }
135
136   for (unsigned int ix = 0; ix < device_count; ix++) {
137
138     unsigned int is_match =
139         ((1 << ix) & conf_match_mask) || (conf_match_mask == 0);
140     if (conf_mask_is_exclude == !!is_match) {
141       continue;
142     }
143
144     nvmlDevice_t dev;
145     TRY(nvmlDeviceGetHandleByIndex(ix, &dev));
146
147     char dev_name[MAX_DEVNAME_LEN + 1] = {0};
148     TRY(nvmlDeviceGetName(dev, dev_name, sizeof(dev_name) - 1));
149
150     // Try to be as lenient as possible with the variety of devices that are
151     // out there, ignoring any NOT_SUPPORTED errors gently.
152     nvmlMemory_t meminfo;
153     TRYOPT(nvmlDeviceGetMemoryInfo(dev, &meminfo))
154     if (nv_status == NVML_SUCCESS) {
155       nvml_submit_gauge(dev_name, "memory", "used", meminfo.used);
156       nvml_submit_gauge(dev_name, "memory", "free", meminfo.free);
157     }
158
159     nvmlUtilization_t utilization;
160     TRYOPT(nvmlDeviceGetUtilizationRates(dev, &utilization))
161     if (nv_status == NVML_SUCCESS)
162       nvml_submit_gauge(dev_name, "percent", "gpu_used", utilization.gpu);
163
164     unsigned int fan_speed;
165     TRYOPT(nvmlDeviceGetFanSpeed(dev, &fan_speed))
166     if (nv_status == NVML_SUCCESS)
167       nvml_submit_gauge(dev_name, "fanspeed", NULL, fan_speed);
168
169     unsigned int core_temp;
170     TRYOPT(nvmlDeviceGetTemperature(dev, NVML_TEMPERATURE_GPU, &core_temp))
171     if (nv_status == NVML_SUCCESS)
172       nvml_submit_gauge(dev_name, "temperature", "core", core_temp);
173
174     unsigned int sm_clk_mhz;
175     TRYOPT(nvmlDeviceGetClockInfo(dev, NVML_CLOCK_SM, &sm_clk_mhz))
176     if (nv_status == NVML_SUCCESS)
177       nvml_submit_gauge(dev_name, "frequency", "sm", 1e6 * sm_clk_mhz);
178
179     unsigned int mem_clk_mhz;
180     TRYOPT(nvmlDeviceGetClockInfo(dev, NVML_CLOCK_MEM, &mem_clk_mhz))
181     if (nv_status == NVML_SUCCESS)
182       nvml_submit_gauge(dev_name, "frequency", "mem", 1e6 * mem_clk_mhz);
183
184     unsigned int power_mW;
185     TRYOPT(nvmlDeviceGetPowerUsage(dev, &power_mW))
186     if (nv_status == NVML_SUCCESS)
187       nvml_submit_gauge(dev_name, "power", NULL, 1e-3 * power_mW);
188
189     continue;
190
191     // Failures here indicate transient errors or removal of GPU. In either
192     // case it will either be resolved or the GPU will no longer be enumerated
193     // the next time round.
194     catch : WARNING(PLUGIN_NAME
195                     ": NVML call \"%s\" failed (%d) on dev at index %d!",
196                     nv_errline, nv_status, ix);
197     continue;
198   }
199
200   return 0;
201
202 // Failures here indicate serious misconfiguration; we bail out totally.
203 catch_nocount:
204   ERROR(PLUGIN_NAME ": Failed to enumerate NVIDIA GPUs (\"%s\" returned %d)",
205         nv_errline, nv_status);
206   return -1;
207 }
208
209 void module_register(void) {
210   plugin_register_init(PLUGIN_NAME, nvml_init);
211   plugin_register_config(PLUGIN_NAME, nvml_config, config_keys, n_config_keys);
212   plugin_register_read(PLUGIN_NAME, nvml_read);
213   plugin_register_shutdown(PLUGIN_NAME, nvml_shutdown);
214 }