contrib/docker: add instructions to README
[collectd.git] / src / dpdkstat.c
1 /*-
2  * collectd - src/dpdkstat.c
3  * MIT License
4  *
5  * Copyright(c) 2016 Intel Corporation. All rights reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23  * SOFTWARE.
24  *
25  * Authors:
26  *   Maryam Tahhan <maryam.tahhan@intel.com>
27  *   Harry van Haaren <harry.van.haaren@intel.com>
28  */
29
30 #include "collectd.h"
31
32 #include "common.h" /* auxiliary functions */
33 #include "plugin.h" /* plugin_register_*, plugin_dispatch_values */
34 #include "utils_time.h"
35
36 #include <getopt.h>
37 #include <semaphore.h>
38 #include <sys/mman.h>
39 #include <sys/queue.h>
40 #include <poll.h>
41
42 #include <rte_config.h>
43 #include <rte_eal.h>
44 #include <rte_ethdev.h>
45 #include <rte_common.h>
46 #include <rte_debug.h>
47 #include <rte_malloc.h>
48 #include <rte_memory.h>
49 #include <rte_memzone.h>
50 #include <rte_launch.h>
51 #include <rte_tailq.h>
52 #include <rte_lcore.h>
53 #include <rte_per_lcore.h>
54 #include <rte_debug.h>
55 #include <rte_log.h>
56 #include <rte_atomic.h>
57 #include <rte_branch_prediction.h>
58 #include <rte_string_fns.h>
59
60 #define DPDK_DEFAULT_RTE_CONFIG "/var/run/.rte_config"
61 #define DPDK_MAX_ARGC 8
62 #define DPDKSTAT_MAX_BUFFER_SIZE (4096 * 4)
63 #define DPDK_SHM_NAME "dpdk_collectd_stats_shm"
64 #define ERR_BUF_SIZE 1024
65 #define REINIT_SHM 1
66 #define RESET 1
67 #define NO_RESET 0
68
69 enum DPDK_HELPER_ACTION {
70   DPDK_HELPER_ACTION_COUNT_STATS,
71   DPDK_HELPER_ACTION_SEND_STATS,
72 };
73
74 enum DPDK_HELPER_STATUS {
75   DPDK_HELPER_NOT_INITIALIZED = 0,
76   DPDK_HELPER_WAITING_ON_PRIMARY,
77   DPDK_HELPER_INITIALIZING_EAL,
78   DPDK_HELPER_ALIVE_SENDING_STATS,
79   DPDK_HELPER_GRACEFUL_QUIT,
80 };
81
82 struct dpdk_config_s {
83   /* General DPDK params */
84   char coremask[DATA_MAX_NAME_LEN];
85   char memory_channels[DATA_MAX_NAME_LEN];
86   char socket_memory[DATA_MAX_NAME_LEN];
87   char process_type[DATA_MAX_NAME_LEN];
88   char file_prefix[DATA_MAX_NAME_LEN];
89   cdtime_t interval;
90   uint32_t eal_initialized;
91   uint32_t enabled_port_mask;
92   char port_name[RTE_MAX_ETHPORTS][DATA_MAX_NAME_LEN];
93   uint32_t eal_argc;
94   /* Helper info */
95   int collectd_reinit_shm;
96   pid_t helper_pid;
97   sem_t sema_helper_get_stats;
98   sem_t sema_stats_in_shm;
99   int helper_pipes[2];
100   enum DPDK_HELPER_STATUS helper_status;
101   enum DPDK_HELPER_ACTION helper_action;
102   /* xstats info */
103   uint32_t num_ports;
104   uint32_t num_xstats;
105   cdtime_t port_read_time[RTE_MAX_ETHPORTS];
106   uint32_t num_stats_in_port[RTE_MAX_ETHPORTS];
107   struct rte_eth_link link_status[RTE_MAX_ETHPORTS];
108   struct rte_eth_xstats *xstats;
109   /* rte_eth_xstats from here on until the end of the SHM */
110 };
111 typedef struct dpdk_config_s dpdk_config_t;
112
113 static int g_configured;
114 static dpdk_config_t *g_configuration;
115
116 static void dpdk_config_init_default(void);
117 static int dpdk_config(oconfig_item_t *ci);
118 static int dpdk_helper_init_eal(void);
119 static int dpdk_helper_run(void);
120 static int dpdk_helper_spawn(enum DPDK_HELPER_ACTION action);
121 static int dpdk_init(void);
122 static int dpdk_read(user_data_t *ud);
123 static int dpdk_shm_cleanup(void);
124 static int dpdk_shm_init(size_t size);
125
126 /* Write the default configuration to the g_configuration instances */
127 static void dpdk_config_init_default(void) {
128   g_configuration->interval = plugin_get_interval();
129   if (g_configuration->interval == cf_get_default_interval())
130     WARNING("dpdkstat: No time interval was configured, default value %lu ms "
131             "is set",
132             CDTIME_T_TO_MS(g_configuration->interval));
133   /* Default is all ports enabled */
134   g_configuration->enabled_port_mask = ~0;
135   g_configuration->eal_argc = DPDK_MAX_ARGC;
136   g_configuration->eal_initialized = 0;
137   ssnprintf(g_configuration->coremask, DATA_MAX_NAME_LEN, "%s", "0xf");
138   ssnprintf(g_configuration->memory_channels, DATA_MAX_NAME_LEN, "%s", "1");
139   ssnprintf(g_configuration->process_type, DATA_MAX_NAME_LEN, "%s",
140             "secondary");
141   ssnprintf(g_configuration->file_prefix, DATA_MAX_NAME_LEN, "%s",
142             DPDK_DEFAULT_RTE_CONFIG);
143
144   for (int i = 0; i < RTE_MAX_ETHPORTS; i++)
145     g_configuration->port_name[i][0] = 0;
146 }
147
148 static int dpdk_config(oconfig_item_t *ci) {
149   int port_counter = 0;
150   /* Allocate g_configuration and
151    * initialize a POSIX SHared Memory (SHM) object.
152    */
153   int err = dpdk_shm_init(sizeof(dpdk_config_t));
154   if (err) {
155     char errbuf[ERR_BUF_SIZE];
156     ERROR("dpdkstat: error in shm_init, %s",
157           sstrerror(errno, errbuf, sizeof(errbuf)));
158     return -1;
159   }
160
161   /* Set defaults for config, overwritten by loop if config item exists */
162   dpdk_config_init_default();
163
164   for (int i = 0; i < ci->children_num; i++) {
165     oconfig_item_t *child = ci->children + i;
166
167     if (strcasecmp("Coremask", child->key) == 0) {
168       cf_util_get_string_buffer(child, g_configuration->coremask,
169                                 sizeof(g_configuration->coremask));
170       DEBUG("dpdkstat:COREMASK %s ", g_configuration->coremask);
171     } else if (strcasecmp("MemoryChannels", child->key) == 0) {
172       cf_util_get_string_buffer(child, g_configuration->memory_channels,
173                                 sizeof(g_configuration->memory_channels));
174       DEBUG("dpdkstat:Memory Channels %s ", g_configuration->memory_channels);
175     } else if (strcasecmp("SocketMemory", child->key) == 0) {
176       cf_util_get_string_buffer(child, g_configuration->socket_memory,
177                                 sizeof(g_configuration->memory_channels));
178       DEBUG("dpdkstat: socket mem %s ", g_configuration->socket_memory);
179     } else if (strcasecmp("ProcessType", child->key) == 0) {
180       cf_util_get_string_buffer(child, g_configuration->process_type,
181                                 sizeof(g_configuration->process_type));
182       DEBUG("dpdkstat: proc type %s ", g_configuration->process_type);
183     } else if ((strcasecmp("FilePrefix", child->key) == 0) &&
184                (child->values[0].type == OCONFIG_TYPE_STRING)) {
185       ssnprintf(g_configuration->file_prefix, DATA_MAX_NAME_LEN,
186                 "/var/run/.%s_config", child->values[0].value.string);
187       DEBUG("dpdkstat: file prefix %s ", g_configuration->file_prefix);
188     } else if ((strcasecmp("EnabledPortMask", child->key) == 0) &&
189                (child->values[0].type == OCONFIG_TYPE_NUMBER)) {
190       g_configuration->enabled_port_mask =
191           (uint32_t)child->values[0].value.number;
192       DEBUG("dpdkstat: Enabled Port Mask %u",
193             g_configuration->enabled_port_mask);
194     } else if (strcasecmp("PortName", child->key) == 0) {
195       cf_util_get_string_buffer(
196           child, g_configuration->port_name[port_counter],
197           sizeof(g_configuration->port_name[port_counter]));
198       DEBUG("dpdkstat: Port %d Name: %s ", port_counter,
199             g_configuration->port_name[port_counter]);
200       port_counter++;
201     } else {
202       WARNING("dpdkstat: The config option \"%s\" is unknown.", child->key);
203     }
204   }                 /* End for (int i = 0; i < ci->children_num; i++)*/
205   g_configured = 1; /* Bypass configuration in dpdk_shm_init(). */
206
207   return 0;
208 }
209
210 /*
211  * Allocate g_configuration and initialize SHared Memory (SHM)
212  * for config and helper process
213  */
214 static int dpdk_shm_init(size_t size) {
215   /*
216    * Check if SHM is already configured: when config items are provided, the
217    * config function initializes SHM. If there is no config, then init() will
218    * just return.
219    */
220   if (g_configuration)
221     return 0;
222
223   char errbuf[ERR_BUF_SIZE];
224
225   /* Create and open a new object, or open an existing object. */
226   int fd = shm_open(DPDK_SHM_NAME, O_CREAT | O_TRUNC | O_RDWR, 0666);
227   if (fd < 0) {
228     WARNING("dpdkstat:Failed to open %s as SHM:%s", DPDK_SHM_NAME,
229             sstrerror(errno, errbuf, sizeof(errbuf)));
230     goto fail;
231   }
232   /* Set the size of the shared memory object. */
233   int ret = ftruncate(fd, size);
234   if (ret != 0) {
235     WARNING("dpdkstat:Failed to resize SHM:%s",
236             sstrerror(errno, errbuf, sizeof(errbuf)));
237     goto fail_close;
238   }
239   /* Map the shared memory object into this process' virtual address space. */
240   g_configuration = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
241   if (g_configuration == MAP_FAILED) {
242     WARNING("dpdkstat:Failed to mmap SHM:%s",
243             sstrerror(errno, errbuf, sizeof(errbuf)));
244     goto fail_close;
245   }
246   /*
247    * Close the file descriptor, the shared memory object still exists
248    * and can only be removed by calling shm_unlink().
249    */
250   close(fd);
251
252   /* Initialize g_configuration. */
253   memset(g_configuration, 0, size);
254
255   /* Initialize the semaphores for SHM use */
256   int err = sem_init(&g_configuration->sema_helper_get_stats, 1, 0);
257   if (err) {
258     ERROR("dpdkstat semaphore init failed: %s",
259           sstrerror(errno, errbuf, sizeof(errbuf)));
260     goto fail_close;
261   }
262   err = sem_init(&g_configuration->sema_stats_in_shm, 1, 0);
263   if (err) {
264     ERROR("dpdkstat semaphore init failed: %s",
265           sstrerror(errno, errbuf, sizeof(errbuf)));
266     goto fail_close;
267   }
268
269   g_configuration->xstats = NULL;
270
271   return 0;
272
273 fail_close:
274   close(fd);
275 fail:
276   /* Reset to zero, as it was set to MAP_FAILED aka: (void *)-1. Avoid
277    * an issue if collectd attempts to run this plugin failure.
278    */
279   g_configuration = 0;
280   return -1;
281 }
282
283 static int dpdk_re_init_shm() {
284   dpdk_config_t temp_config;
285   memcpy(&temp_config, g_configuration, sizeof(dpdk_config_t));
286   DEBUG("dpdkstat: %s: ports %" PRIu32 ", xstats %" PRIu32, __func__,
287         temp_config.num_ports, temp_config.num_xstats);
288
289   size_t shm_xstats_size =
290       sizeof(dpdk_config_t) +
291       (sizeof(struct rte_eth_xstats) * g_configuration->num_xstats);
292   DEBUG("=== SHM new size for %" PRIu32 " xstats", g_configuration->num_xstats);
293
294   int err = dpdk_shm_cleanup();
295   if (err) {
296     ERROR("dpdkstat: Error in shm_cleanup in %s", __func__);
297     return err;
298   }
299   err = dpdk_shm_init(shm_xstats_size);
300   if (err) {
301     WARNING("dpdkstat: Error in shm_init in %s", __func__);
302     return err;
303   }
304   /* If the XML config() function has been run, don't re-initialize defaults */
305   if (!g_configured)
306     dpdk_config_init_default();
307
308   memcpy(g_configuration, &temp_config, sizeof(dpdk_config_t));
309   g_configuration->collectd_reinit_shm = 0;
310   g_configuration->xstats = (struct rte_eth_xstats *)(g_configuration + 1);
311   return 0;
312 }
313
314 static int dpdk_init(void) {
315   int err = dpdk_shm_init(sizeof(dpdk_config_t));
316   if (err) {
317     ERROR("dpdkstat: %s : error %d in shm_init()", __func__, err);
318     return err;
319   }
320
321   /* If the XML config() function has been run, dont re-initialize defaults */
322   if (!g_configured) {
323     dpdk_config_init_default();
324   }
325
326   return 0;
327 }
328
329 static int dpdk_helper_stop(int reset) {
330   g_configuration->helper_status = DPDK_HELPER_GRACEFUL_QUIT;
331   if (reset) {
332     g_configuration->eal_initialized = 0;
333     g_configuration->num_ports = 0;
334     g_configuration->xstats = NULL;
335     g_configuration->num_xstats = 0;
336     for (int i = 0; i < RTE_MAX_ETHPORTS; i++)
337       g_configuration->num_stats_in_port[i] = 0;
338   }
339   close(g_configuration->helper_pipes[1]);
340   int err = kill(g_configuration->helper_pid, SIGKILL);
341   if (err) {
342     char errbuf[ERR_BUF_SIZE];
343     WARNING("dpdkstat: error sending kill to helper: %s",
344             sstrerror(errno, errbuf, sizeof(errbuf)));
345   }
346
347   return 0;
348 }
349
350 static int dpdk_helper_spawn(enum DPDK_HELPER_ACTION action) {
351   char errbuf[ERR_BUF_SIZE];
352   g_configuration->eal_initialized = 0;
353   g_configuration->helper_action = action;
354   /*
355    * Create a pipe for helper stdout back to collectd. This is necessary for
356    * logging EAL failures, as rte_eal_init() calls rte_panic().
357    */
358   if (pipe(g_configuration->helper_pipes) != 0) {
359     DEBUG("dpdkstat: Could not create helper pipe: %s",
360           sstrerror(errno, errbuf, sizeof(errbuf)));
361     return -1;
362   }
363
364   int pipe0_flags = fcntl(g_configuration->helper_pipes[0], F_GETFL, 0);
365   int pipe1_flags = fcntl(g_configuration->helper_pipes[1], F_GETFL, 0);
366   if (pipe0_flags == -1 || pipe1_flags == -1) {
367     WARNING("dpdkstat: Failed setting up pipe flags: %s",
368             sstrerror(errno, errbuf, sizeof(errbuf)));
369   }
370   int pipe0_err = fcntl(g_configuration->helper_pipes[0], F_SETFL,
371                         pipe1_flags | O_NONBLOCK);
372   int pipe1_err = fcntl(g_configuration->helper_pipes[1], F_SETFL,
373                         pipe0_flags | O_NONBLOCK);
374   if (pipe0_err == -1 || pipe1_err == -1) {
375     WARNING("dpdkstat: Failed setting up pipes: %s",
376             sstrerror(errno, errbuf, sizeof(errbuf)));
377   }
378
379   pid_t pid = fork();
380   if (pid > 0) {
381     close(g_configuration->helper_pipes[1]);
382     g_configuration->helper_pid = pid;
383     DEBUG("dpdkstat: helper pid %lu", (long)g_configuration->helper_pid);
384     /* Kick helper once its alive to have it start processing */
385     sem_post(&g_configuration->sema_helper_get_stats);
386   } else if (pid == 0) {
387     /* Replace stdout with a pipe to collectd. */
388     close(g_configuration->helper_pipes[0]);
389     close(STDOUT_FILENO);
390     dup2(g_configuration->helper_pipes[1], STDOUT_FILENO);
391     dpdk_helper_run();
392     exit(0);
393   } else {
394     ERROR("dpdkstat: Failed to fork helper process: %s",
395           sstrerror(errno, errbuf, sizeof(errbuf)));
396     return -1;
397   }
398   return 0;
399 }
400
401 /*
402  * Initialize the DPDK EAL, if this returns, EAL is successfully initialized.
403  * On failure, the EAL prints an error message, and the helper process exits.
404  */
405 static int dpdk_helper_init_eal(void) {
406   g_configuration->helper_status = DPDK_HELPER_INITIALIZING_EAL;
407   char *argp[(g_configuration->eal_argc) + 1];
408   int i = 0;
409
410   argp[i++] = "collectd-dpdk";
411   if (strcasecmp(g_configuration->coremask, "") != 0) {
412     argp[i++] = "-c";
413     argp[i++] = g_configuration->coremask;
414   }
415   if (strcasecmp(g_configuration->memory_channels, "") != 0) {
416     argp[i++] = "-n";
417     argp[i++] = g_configuration->memory_channels;
418   }
419   if (strcasecmp(g_configuration->socket_memory, "") != 0) {
420     argp[i++] = "--socket-mem";
421     argp[i++] = g_configuration->socket_memory;
422   }
423   if (strcasecmp(g_configuration->file_prefix, "") != 0 &&
424       strcasecmp(g_configuration->file_prefix, DPDK_DEFAULT_RTE_CONFIG) != 0) {
425     argp[i++] = "--file-prefix";
426     argp[i++] = g_configuration->file_prefix;
427   }
428   if (strcasecmp(g_configuration->process_type, "") != 0) {
429     argp[i++] = "--proc-type";
430     argp[i++] = g_configuration->process_type;
431   }
432   g_configuration->eal_argc = i;
433
434   g_configuration->eal_initialized = 1;
435   int ret = rte_eal_init(g_configuration->eal_argc, argp);
436   if (ret < 0) {
437     g_configuration->eal_initialized = 0;
438     return ret;
439   }
440   return 0;
441 }
442
443 static int dpdk_helper_run(void) {
444   char errbuf[ERR_BUF_SIZE];
445   pid_t ppid = getppid();
446   g_configuration->helper_status = DPDK_HELPER_WAITING_ON_PRIMARY;
447
448   while (1) {
449     /* sem_timedwait() to avoid blocking forever */
450     cdtime_t now = cdtime();
451     cdtime_t safety_period = MS_TO_CDTIME_T(1500);
452     int ret =
453         sem_timedwait(&g_configuration->sema_helper_get_stats,
454                       &CDTIME_T_TO_TIMESPEC(now + safety_period +
455                                             g_configuration->interval * 2));
456
457     if (ret == -1 && errno == ETIMEDOUT) {
458       ERROR("dpdkstat-helper: sem timedwait()"
459             " timeout, did collectd terminate?");
460       dpdk_helper_stop(RESET);
461     }
462     /* Parent PID change means collectd died so quit the helper process. */
463     if (ppid != getppid()) {
464       WARNING("dpdkstat-helper: parent PID changed, quitting.");
465       dpdk_helper_stop(RESET);
466     }
467
468     /* Checking for DPDK primary process. */
469     if (!rte_eal_primary_proc_alive(g_configuration->file_prefix)) {
470       if (g_configuration->eal_initialized) {
471         WARNING("dpdkstat-helper: no primary alive but EAL initialized:"
472                 " quitting.");
473         dpdk_helper_stop(RESET);
474       }
475       g_configuration->helper_status = DPDK_HELPER_WAITING_ON_PRIMARY;
476       /* Back to start of while() - waiting for primary process */
477       continue;
478     }
479
480     if (!g_configuration->eal_initialized) {
481       /* Initialize EAL. */
482       int ret = dpdk_helper_init_eal();
483       if (ret != 0) {
484         WARNING("ERROR INITIALIZING EAL");
485         dpdk_helper_stop(RESET);
486       }
487     }
488
489     g_configuration->helper_status = DPDK_HELPER_ALIVE_SENDING_STATS;
490
491     uint8_t nb_ports = rte_eth_dev_count();
492     if (nb_ports == 0) {
493       DEBUG("dpdkstat-helper: No DPDK ports available. "
494             "Check bound devices to DPDK driver.");
495       dpdk_helper_stop(RESET);
496     }
497
498     if (nb_ports > RTE_MAX_ETHPORTS)
499       nb_ports = RTE_MAX_ETHPORTS;
500
501     int len = 0, enabled_port_count = 0, num_xstats = 0;
502     for (uint8_t i = 0; i < nb_ports; i++) {
503       if (!(g_configuration->enabled_port_mask & (1 << i)))
504         continue;
505
506       if (g_configuration->helper_action == DPDK_HELPER_ACTION_COUNT_STATS) {
507         len = rte_eth_xstats_get(i, NULL, 0);
508         if (len < 0) {
509           ERROR("dpdkstat-helper: Cannot get xstats count on port %" PRIu8, i);
510           break;
511         }
512         num_xstats += len;
513         g_configuration->num_stats_in_port[enabled_port_count] = len;
514         enabled_port_count++;
515         continue;
516       } else {
517         len = g_configuration->num_stats_in_port[enabled_port_count];
518         g_configuration->port_read_time[enabled_port_count] = cdtime();
519         ret = rte_eth_xstats_get(
520             i, g_configuration->xstats + num_xstats,
521             g_configuration->num_stats_in_port[enabled_port_count]);
522         if (ret < 0 || ret != len) {
523           DEBUG("dpdkstat-helper: Error reading xstats on port %" PRIu8
524                 " len = %d",
525                 i, len);
526           break;
527         }
528         num_xstats += g_configuration->num_stats_in_port[enabled_port_count];
529         enabled_port_count++;
530       }
531     } /* for (nb_ports) */
532
533     if (g_configuration->helper_action == DPDK_HELPER_ACTION_COUNT_STATS) {
534       g_configuration->num_ports = enabled_port_count;
535       g_configuration->num_xstats = num_xstats;
536       DEBUG("dpdkstat-helper ports: %" PRIu32 ", num stats: %" PRIu32,
537             g_configuration->num_ports, g_configuration->num_xstats);
538       /* Exit, allowing collectd to re-init SHM to the right size */
539       g_configuration->collectd_reinit_shm = REINIT_SHM;
540       dpdk_helper_stop(NO_RESET);
541     }
542     /* Now kick collectd send thread to send the stats */
543     int err = sem_post(&g_configuration->sema_stats_in_shm);
544     if (err) {
545       WARNING("dpdkstat: error posting semaphore to helper %s",
546               sstrerror(errno, errbuf, sizeof(errbuf)));
547       dpdk_helper_stop(RESET);
548     }
549   } /* while(1) */
550
551   return 0;
552 }
553
554 static void dpdk_submit_xstats(const char *dev_name,
555                                const struct rte_eth_xstats *xstats,
556                                uint32_t counters, cdtime_t port_read_time) {
557   for (uint32_t j = 0; j < counters; j++) {
558     value_list_t vl = VALUE_LIST_INIT;
559     char *type_end;
560
561     vl.values = &(value_t){.derive = (derive_t)xstats[j].value};
562     vl.values_len = 1; /* Submit stats one at a time */
563     vl.time = port_read_time;
564     sstrncpy(vl.plugin, "dpdkstat", sizeof(vl.plugin));
565     sstrncpy(vl.plugin_instance, dev_name, sizeof(vl.plugin_instance));
566
567     type_end = strrchr(xstats[j].name, '_');
568
569     if ((type_end != NULL) &&
570         (strncmp(xstats[j].name, "rx_", strlen("rx_")) == 0)) {
571       if (strncmp(type_end, "_errors", strlen("_errors")) == 0) {
572         sstrncpy(vl.type, "if_rx_errors", sizeof(vl.type));
573       } else if (strncmp(type_end, "_dropped", strlen("_dropped")) == 0) {
574         sstrncpy(vl.type, "if_rx_dropped", sizeof(vl.type));
575       } else if (strncmp(type_end, "_bytes", strlen("_bytes")) == 0) {
576         sstrncpy(vl.type, "if_rx_octets", sizeof(vl.type));
577       } else if (strncmp(type_end, "_packets", strlen("_packets")) == 0) {
578         sstrncpy(vl.type, "if_rx_packets", sizeof(vl.type));
579       } else if (strncmp(type_end, "_placement", strlen("_placement")) == 0) {
580         sstrncpy(vl.type, "if_rx_errors", sizeof(vl.type));
581       } else if (strncmp(type_end, "_buff", strlen("_buff")) == 0) {
582         sstrncpy(vl.type, "if_rx_errors", sizeof(vl.type));
583       } else {
584         /* Does not fit obvious type: use a more generic one */
585         sstrncpy(vl.type, "derive", sizeof(vl.type));
586       }
587
588     } else if ((type_end != NULL) &&
589                (strncmp(xstats[j].name, "tx_", strlen("tx_"))) == 0) {
590       if (strncmp(type_end, "_errors", strlen("_errors")) == 0) {
591         sstrncpy(vl.type, "if_tx_errors", sizeof(vl.type));
592       } else if (strncmp(type_end, "_dropped", strlen("_dropped")) == 0) {
593         sstrncpy(vl.type, "if_tx_dropped", sizeof(vl.type));
594       } else if (strncmp(type_end, "_bytes", strlen("_bytes")) == 0) {
595         sstrncpy(vl.type, "if_tx_octets", sizeof(vl.type));
596       } else if (strncmp(type_end, "_packets", strlen("_packets")) == 0) {
597         sstrncpy(vl.type, "if_tx_packets", sizeof(vl.type));
598       } else {
599         /* Does not fit obvious type: use a more generic one */
600         sstrncpy(vl.type, "derive", sizeof(vl.type));
601       }
602     } else if ((type_end != NULL) &&
603                (strncmp(xstats[j].name, "flow_", strlen("flow_"))) == 0) {
604
605       if (strncmp(type_end, "_filters", strlen("_filters")) == 0) {
606         sstrncpy(vl.type, "operations", sizeof(vl.type));
607       } else if (strncmp(type_end, "_errors", strlen("_errors")) == 0) {
608         sstrncpy(vl.type, "errors", sizeof(vl.type));
609       } else if (strncmp(type_end, "_filters", strlen("_filters")) == 0) {
610         sstrncpy(vl.type, "filter_result", sizeof(vl.type));
611       }
612     } else if ((type_end != NULL) &&
613                (strncmp(xstats[j].name, "mac_", strlen("mac_"))) == 0) {
614       if (strncmp(type_end, "_errors", strlen("_errors")) == 0) {
615         sstrncpy(vl.type, "errors", sizeof(vl.type));
616       }
617     } else {
618       /* Does not fit obvious type, or strrchr error:
619        *   use a more generic type */
620       sstrncpy(vl.type, "derive", sizeof(vl.type));
621     }
622
623     sstrncpy(vl.type_instance, xstats[j].name, sizeof(vl.type_instance));
624     plugin_dispatch_values(&vl);
625   }
626 }
627
628 static int dpdk_read(user_data_t *ud) {
629   int ret = 0;
630
631   /*
632    * Check if SHM flag is set to be re-initialized. AKA DPDK ports have been
633    * counted, so re-init SHM to be large enough to fit all the statistics.
634    */
635   if (g_configuration->collectd_reinit_shm) {
636     DEBUG("dpdkstat: read() now reinit SHM then launching send-thread");
637     dpdk_re_init_shm();
638   }
639
640   /*
641    * Check if DPDK proc is alive, and has already counted port / stats. This
642    * must be done in dpdk_read(), because the DPDK primary process may not be
643    * alive at dpdk_init() time.
644    */
645   if (g_configuration->helper_status == DPDK_HELPER_NOT_INITIALIZED ||
646       g_configuration->helper_status == DPDK_HELPER_GRACEFUL_QUIT) {
647     int action = DPDK_HELPER_ACTION_SEND_STATS;
648     if (g_configuration->num_xstats == 0)
649       action = DPDK_HELPER_ACTION_COUNT_STATS;
650     /* Spawn the helper thread to count stats or to read stats. */
651     int err = dpdk_helper_spawn(action);
652     if (err) {
653       char errbuf[ERR_BUF_SIZE];
654       ERROR("dpdkstat: error spawning helper %s",
655             sstrerror(errno, errbuf, sizeof(errbuf)));
656       return -1;
657     }
658   }
659
660   pid_t ws = waitpid(g_configuration->helper_pid, NULL, WNOHANG);
661   /*
662    * Conditions under which to respawn helper:
663    *  waitpid() fails, helper process died (or quit), so respawn
664    */
665   _Bool respawn_helper = 0;
666   if (ws != 0) {
667     respawn_helper = 1;
668   }
669
670   char buf[DPDKSTAT_MAX_BUFFER_SIZE];
671   char out[DPDKSTAT_MAX_BUFFER_SIZE];
672
673   /* non blocking check on helper logging pipe */
674   struct pollfd fds = {
675       .fd = g_configuration->helper_pipes[0], .events = POLLIN,
676   };
677   int data_avail = poll(&fds, 1, 0);
678   if (data_avail < 0) {
679     char errbuf[ERR_BUF_SIZE];
680     if (errno != EINTR || errno != EAGAIN)
681       ERROR("dpdkstats: poll(2) failed: %s",
682             sstrerror(errno, errbuf, sizeof(errbuf)));
683   }
684   while (data_avail) {
685     int nbytes = read(g_configuration->helper_pipes[0], buf, sizeof(buf));
686     if (nbytes <= 0)
687       break;
688     ssnprintf(out, nbytes, "%s", buf);
689     DEBUG("dpdkstat: helper-proc: %s", out);
690   }
691
692   if (respawn_helper) {
693     if (g_configuration->helper_pid)
694       dpdk_helper_stop(RESET);
695     dpdk_helper_spawn(DPDK_HELPER_ACTION_COUNT_STATS);
696   }
697
698   /* Kick helper process through SHM */
699   sem_post(&g_configuration->sema_helper_get_stats);
700
701   cdtime_t now = cdtime();
702   ret = sem_timedwait(&g_configuration->sema_stats_in_shm,
703                       &CDTIME_T_TO_TIMESPEC(now + g_configuration->interval));
704   if (ret == -1) {
705     if (errno == ETIMEDOUT)
706       DEBUG(
707           "dpdkstat: timeout in collectd thread: is a DPDK Primary running? ");
708     return 0;
709   }
710
711   /* Dispatch the stats.*/
712   uint32_t count = 0, port_num = 0;
713
714   for (uint32_t i = 0; i < g_configuration->num_ports; i++) {
715     char dev_name[64];
716     cdtime_t port_read_time = g_configuration->port_read_time[i];
717     uint32_t counters_num = g_configuration->num_stats_in_port[i];
718     size_t ports_max = CHAR_BIT * sizeof(g_configuration->enabled_port_mask);
719     for (size_t j = port_num; j < ports_max; j++) {
720       if ((g_configuration->enabled_port_mask & (1 << j)) != 0)
721         break;
722       port_num++;
723     }
724
725     if (g_configuration->port_name[i][0] != 0)
726       ssnprintf(dev_name, sizeof(dev_name), "%s",
727                 g_configuration->port_name[i]);
728     else
729       ssnprintf(dev_name, sizeof(dev_name), "port.%" PRIu32, port_num);
730     struct rte_eth_xstats *xstats = g_configuration->xstats + count;
731
732     dpdk_submit_xstats(dev_name, xstats, counters_num, port_read_time);
733     count += counters_num;
734     port_num++;
735   } /* for each port */
736   return 0;
737 }
738
739 static int dpdk_shm_cleanup(void) {
740   int ret = munmap(g_configuration, sizeof(dpdk_config_t));
741   g_configuration = 0;
742   if (ret) {
743     ERROR("dpdkstat: munmap returned %d", ret);
744     return ret;
745   }
746   ret = shm_unlink(DPDK_SHM_NAME);
747   if (ret) {
748     ERROR("dpdkstat: shm_unlink returned %d", ret);
749     return ret;
750   }
751   return 0;
752 }
753
754 static int dpdk_shutdown(void) {
755   int ret = 0;
756   char errbuf[ERR_BUF_SIZE];
757   close(g_configuration->helper_pipes[1]);
758   int err = kill(g_configuration->helper_pid, SIGKILL);
759   if (err) {
760     ERROR("dpdkstat: error sending sigkill to helper %s",
761           sstrerror(errno, errbuf, sizeof(errbuf)));
762     ret = -1;
763   }
764   err = dpdk_shm_cleanup();
765   if (err) {
766     ERROR("dpdkstat: error cleaning up SHM: %s",
767           sstrerror(errno, errbuf, sizeof(errbuf)));
768     ret = -1;
769   }
770
771   return ret;
772 }
773
774 void module_register(void) {
775   plugin_register_complex_config("dpdkstat", dpdk_config);
776   plugin_register_init("dpdkstat", dpdk_init);
777   plugin_register_complex_read(NULL, "dpdkstat", dpdk_read, 0, NULL);
778   plugin_register_shutdown("dpdkstat", dpdk_shutdown);
779 }