Remove parentheses around return arguments
[collectd.git] / src / ovs_stats.c
1 /*
2  * collectd - src/ovs_stats.c
3  *
4  * Copyright(c) 2016 Intel Corporation. All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  *
24  * Authors:
25  *   Taras Chornyi <tarasx.chornyi@intel.com>
26  */
27
28 #include "common.h"
29
30 #include "utils_ovs.h" /* OvS helpers */
31
32 /* Plugin name */
33 static const char plugin_name[] = "ovs_stats";
34
35 typedef enum iface_counter {
36   not_supported = -1,
37   collisions,
38   rx_bytes,
39   rx_crc_err,
40   rx_dropped,
41   rx_errors,
42   rx_frame_err,
43   rx_over_err,
44   rx_packets,
45   tx_bytes,
46   tx_dropped,
47   tx_errors,
48   tx_packets,
49   rx_1_to_64_packets,
50   rx_65_to_127_packets,
51   rx_128_to_255_packets,
52   rx_256_to_511_packets,
53   rx_512_to_1023_packets,
54   rx_1024_to_1522_packets,
55   rx_1523_to_max_packets,
56   tx_1_to_64_packets,
57   tx_65_to_127_packets,
58   tx_128_to_255_packets,
59   tx_256_to_511_packets,
60   tx_512_to_1023_packets,
61   tx_1024_to_1522_packets,
62   tx_1523_to_max_packets,
63   tx_multicast_packets,
64   rx_broadcast_packets,
65   tx_broadcast_packets,
66   rx_undersized_errors,
67   rx_oversize_errors,
68   rx_fragmented_errors,
69   rx_jabber_errors,
70   __iface_counter_max
71 } iface_counter;
72
73 #define IFACE_COUNTER_MAX (__iface_counter_max - 1)
74 #define IFACE_COUNTER_COUNT (__iface_counter_max)
75 #define PORT_NAME_SIZE_MAX 255
76 #define UUID_SIZE 64
77
78 typedef struct port_s {
79   char name[PORT_NAME_SIZE_MAX];      /* Port name */
80   char port_uuid[UUID_SIZE];          /* Port table _uuid */
81   char iface_uuid[UUID_SIZE];         /* Interface table uuid */
82   char ex_iface_id[UUID_SIZE];        /* External iface id */
83   char ex_vm_id[UUID_SIZE];           /* External vm id */
84   int64_t stats[IFACE_COUNTER_COUNT]; /* Port statistics */
85   struct bridge_list_s *br;           /* Pointer to bridge */
86   struct port_s *next;                /* Next port */
87 } port_list_t;
88
89 typedef struct bridge_list_s {
90   char *name;                 /* Bridge name */
91   struct bridge_list_s *next; /* Next bridge*/
92 } bridge_list_t;
93
94 static const char *const iface_counter_table[IFACE_COUNTER_COUNT] = {
95         [collisions] = "collisions",
96         [rx_bytes] = "rx_bytes",
97         [rx_crc_err] = "rx_crc_err",
98         [rx_dropped] = "rx_dropped",
99         [rx_errors] = "rx_errors",
100         [rx_frame_err] = "rx_frame_err",
101         [rx_over_err] = "rx_over_err",
102         [rx_packets] = "rx_packets",
103         [tx_bytes] = "tx_bytes",
104         [tx_dropped] = "tx_dropped",
105         [tx_errors] = "tx_errors",
106         [tx_packets] = "tx_packets",
107         [rx_1_to_64_packets] = "rx_1_to_64_packets",
108         [rx_65_to_127_packets] = "rx_65_to_127_packets",
109         [rx_128_to_255_packets] = "rx_128_to_255_packets",
110         [rx_256_to_511_packets] = "rx_256_to_511_packets",
111         [rx_512_to_1023_packets] = "rx_512_to_1023_packets",
112         [rx_1024_to_1522_packets] = "rx_1024_to_1518_packets",
113         [rx_1523_to_max_packets] = "rx_1523_to_max_packets",
114         [tx_1_to_64_packets] = "tx_1_to_64_packets",
115         [tx_65_to_127_packets] = "tx_65_to_127_packets",
116         [tx_128_to_255_packets] = "tx_128_to_255_packets",
117         [tx_256_to_511_packets] = "tx_256_to_511_packets",
118         [tx_512_to_1023_packets] = "tx_512_to_1023_packets",
119         [tx_1024_to_1522_packets] = "tx_1024_to_1518_packets",
120         [tx_1523_to_max_packets] = "tx_1523_to_max_packets",
121         [tx_multicast_packets] = "tx_multicast_packets",
122         [rx_broadcast_packets] = "rx_broadcast_packets",
123         [tx_broadcast_packets] = "tx_broadcast_packets",
124         [rx_undersized_errors] = "rx_undersized_errors",
125         [rx_oversize_errors] = "rx_oversize_errors",
126         [rx_fragmented_errors] = "rx_fragmented_errors",
127         [rx_jabber_errors] = "rx_jabber_errors",
128 };
129
130 /* Entry into the list of network bridges */
131 static bridge_list_t *g_bridge_list_head;
132
133 /* Entry into the list of monitored network bridges */
134 static bridge_list_t *g_monitored_bridge_list_head;
135
136 /* entry into the list of network bridges */
137 static port_list_t *g_port_list_head;
138
139 /* lock for statistics cache */
140 static pthread_mutex_t g_stats_lock;
141
142 /* OvS DB socket */
143 static ovs_db_t *g_ovs_db;
144
145 /* OVS stats configuration data */
146 struct ovs_stats_config_s {
147   char ovs_db_node[OVS_DB_ADDR_NODE_SIZE];    /* OVS DB node */
148   char ovs_db_serv[OVS_DB_ADDR_SERVICE_SIZE]; /* OVS DB service */
149   char ovs_db_unix[OVS_DB_ADDR_UNIX_SIZE];    /* OVS DB unix socket path */
150 };
151 typedef struct ovs_stats_config_s ovs_stats_config_t;
152
153 static ovs_stats_config_t ovs_stats_cfg = {
154     .ovs_db_node = "localhost", /* use default OVS DB node */
155     .ovs_db_serv = "6640",      /* use default OVS DB service */
156 };
157
158 static iface_counter ovs_stats_counter_name_to_type(const char *counter) {
159   iface_counter index = not_supported;
160
161   if (counter == NULL)
162     return not_supported;
163
164   for (int i = 0; i < IFACE_COUNTER_COUNT; i++) {
165     if (strncmp(iface_counter_table[i], counter,
166                 strlen(iface_counter_table[i])) == 0) {
167       index = i;
168       break;
169     }
170   }
171   return index;
172 }
173
174 static void ovs_stats_submit_one(const char *dev, const char *type,
175                                  const char *type_instance, derive_t value,
176                                  meta_data_t *meta) {
177   /* if counter is less than 0 - skip it*/
178   if (value < 0)
179     return;
180   value_list_t vl = VALUE_LIST_INIT;
181
182   vl.values = &(value_t){.derive = value};
183   vl.values_len = 1;
184   vl.meta = meta;
185
186   sstrncpy(vl.plugin, plugin_name, sizeof(vl.plugin));
187   sstrncpy(vl.plugin_instance, dev, sizeof(vl.plugin_instance));
188   sstrncpy(vl.type, type, sizeof(vl.type));
189
190   if (type_instance != NULL)
191     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
192
193   plugin_dispatch_values(&vl);
194 }
195
196 static void ovs_stats_submit_two(const char *dev, const char *type,
197                                  const char *type_instance, derive_t rx,
198                                  derive_t tx, meta_data_t *meta) {
199   /* if counter is less than 0 - skip it*/
200   if (rx < 0 || tx < 0)
201     return;
202   value_list_t vl = VALUE_LIST_INIT;
203   value_t values[] = {{.derive = rx}, {.derive = tx}};
204
205   vl.values = values;
206   vl.values_len = STATIC_ARRAY_SIZE(values);
207   vl.meta = meta;
208
209   sstrncpy(vl.plugin, plugin_name, sizeof(vl.plugin));
210   sstrncpy(vl.plugin_instance, dev, sizeof(vl.plugin_instance));
211   sstrncpy(vl.type, type, sizeof(vl.type));
212
213   if (type_instance != NULL)
214     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
215
216   plugin_dispatch_values(&vl);
217 }
218
219 static port_list_t *ovs_stats_get_port(const char *uuid) {
220   if (uuid == NULL)
221     return NULL;
222
223   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
224     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0)
225       return port;
226   }
227   return NULL;
228 }
229
230 static port_list_t *ovs_stats_get_port_by_name(const char *name) {
231   if (name == NULL)
232     return NULL;
233
234   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next)
235     if ((strncmp(port->name, name, strlen(port->name)) == 0) &&
236         strlen(name) == strlen(port->name))
237       return port;
238   return NULL;
239 }
240
241 /* Create or get port by port uuid */
242 static port_list_t *ovs_stats_new_port(bridge_list_t *bridge,
243                                        const char *uuid) {
244   port_list_t *port = ovs_stats_get_port(uuid);
245
246   if (port == NULL) {
247     port = (port_list_t *)calloc(1, sizeof(port_list_t));
248     if (!port) {
249       ERROR("%s: Error allocating port", plugin_name);
250       return NULL;
251     }
252     memset(port->stats, -1, sizeof(int64_t[IFACE_COUNTER_COUNT]));
253     sstrncpy(port->port_uuid, uuid, sizeof(port->port_uuid));
254     pthread_mutex_lock(&g_stats_lock);
255     port->next = g_port_list_head;
256     g_port_list_head = port;
257     pthread_mutex_unlock(&g_stats_lock);
258   }
259   if (bridge != NULL) {
260     pthread_mutex_lock(&g_stats_lock);
261     port->br = bridge;
262     pthread_mutex_unlock(&g_stats_lock);
263   }
264   return port;
265 }
266
267 /* Get bridge by name*/
268 static bridge_list_t *ovs_stats_get_bridge(bridge_list_t *head,
269                                            const char *name) {
270   if (name == NULL)
271     return NULL;
272
273   for (bridge_list_t *bridge = head; bridge != NULL; bridge = bridge->next) {
274     if ((strncmp(bridge->name, name, strlen(bridge->name)) == 0) &&
275         strlen(name) == strlen(bridge->name))
276       return bridge;
277   }
278   return NULL;
279 }
280
281 /* Delete bridge */
282 static int ovs_stats_del_bridge(yajl_val bridge) {
283   const char *old[] = {"old", NULL};
284   const char *name[] = {"name", NULL};
285
286   yajl_val row;
287
288   if (bridge && YAJL_IS_OBJECT(bridge)) {
289     row = yajl_tree_get(bridge, old, yajl_t_object);
290     if (row && YAJL_IS_OBJECT(row)) {
291       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
292       if (br_name && YAJL_IS_STRING(br_name)) {
293         bridge_list_t *prev_br = g_bridge_list_head;
294         for (bridge_list_t *br = g_bridge_list_head; br != NULL;
295              prev_br = br, br = br->next) {
296           if ((strncmp(br->name, br_name->u.string, strlen(br->name)) == 0) &&
297               strlen(br->name) == strlen(br_name->u.string)) {
298             if (br == g_bridge_list_head)
299               g_bridge_list_head = br->next;
300             else
301               prev_br->next = br->next;
302             sfree(br->name);
303             sfree(br);
304             break;
305           }
306         }
307       }
308     }
309   } else
310     WARNING("%s: Incorrect data for deleting bridge", plugin_name);
311   return 0;
312 }
313
314 /* Update Bridge. Create bridge ports*/
315 static int ovs_stats_update_bridge(yajl_val bridge) {
316   const char *new[] = {"new", NULL};
317   const char *name[] = {"name", NULL};
318   const char *ports[] = {"ports", NULL};
319   bridge_list_t *br = NULL;
320
321   if (bridge && YAJL_IS_OBJECT(bridge)) {
322     yajl_val row = yajl_tree_get(bridge, new, yajl_t_object);
323     if (row && YAJL_IS_OBJECT(row)) {
324       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
325       yajl_val br_ports = yajl_tree_get(row, ports, yajl_t_array);
326       if (br_name && YAJL_IS_STRING(br_name)) {
327         br = ovs_stats_get_bridge(g_bridge_list_head, YAJL_GET_STRING(br_name));
328         pthread_mutex_lock(&g_stats_lock);
329         if (br == NULL) {
330           br = (bridge_list_t *)calloc(1, sizeof(bridge_list_t));
331           if (!br) {
332             ERROR("%s: Error allocating memory for bridge", plugin_name);
333             return -1;
334           }
335           char *tmp = YAJL_GET_STRING(br_name);
336
337           if (tmp != NULL)
338             br->name = strdup(tmp);
339           if (br->name == NULL) {
340             sfree(br);
341             pthread_mutex_unlock(&g_stats_lock);
342             return -1;
343           }
344           br->next = g_bridge_list_head;
345           g_bridge_list_head = br;
346         }
347         pthread_mutex_unlock(&g_stats_lock);
348       }
349       if (br_ports && YAJL_IS_ARRAY(br_ports)) {
350         char *tmp = YAJL_GET_STRING(br_ports->u.array.values[0]);
351         if (tmp != NULL && strcmp("set", tmp) == 0) {
352           yajl_val *array = YAJL_GET_ARRAY(br_ports)->values;
353           size_t array_len = YAJL_GET_ARRAY(br_ports)->len;
354           if (array != NULL && array_len > 0 && YAJL_IS_ARRAY(array[1])) {
355             yajl_val *ports_arr = YAJL_GET_ARRAY(array[1])->values;
356             size_t ports_num = YAJL_GET_ARRAY(array[1])->len;
357             for (size_t i = 0; i < ports_num && ports_arr != NULL; i++)
358               ovs_stats_new_port(
359                   br, YAJL_GET_STRING(ports_arr[i]->u.array.values[1]));
360           }
361         } else
362           ovs_stats_new_port(br, YAJL_GET_STRING(br_ports->u.array.values[1]));
363       }
364     }
365   } else {
366     ERROR("Incorrect JSON Bridge data");
367     return -1;
368   }
369   return 0;
370 }
371
372 /* Handle JSON with Bridge Table change event */
373 static void ovs_stats_bridge_table_change_cb(yajl_val jupdates) {
374   /* Bridge Table update example JSON data
375     {
376       "Bridge": {
377         "bb1f8965-5775-46d9-b820-236ca8edbedc": {
378           "new": {
379             "name": "br0",
380             "ports": [
381               "set",
382               [
383                 [
384                   "uuid",
385                   "117f1a07-7ef0-458a-865c-ec7fbb85bc01"
386                 ],
387                 [
388                   "uuid",
389                   "12fd8bdc-e950-4281-aaa9-46e185658f79"
390                 ]
391               ]
392             ]
393           }
394         }
395       }
396     }
397    */
398   const char *path[] = {"Bridge", NULL};
399
400   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
401
402   if (bridges && YAJL_IS_OBJECT(bridges)) {
403     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
404       yajl_val bridge = YAJL_GET_OBJECT(bridges)->values[i];
405       ovs_stats_update_bridge(bridge);
406     }
407   }
408 }
409
410 /* Handle Bridge Table delete event */
411 static void ovs_stats_bridge_table_delete_cb(yajl_val jupdates) {
412   const char *path[] = {"Bridge", NULL};
413   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
414   yajl_val bridge;
415   if (bridges && YAJL_IS_OBJECT(bridges)) {
416     pthread_mutex_lock(&g_stats_lock);
417     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
418       bridge = YAJL_GET_OBJECT(bridges)->values[i];
419       ovs_stats_del_bridge(bridge);
420     }
421     pthread_mutex_unlock(&g_stats_lock);
422   }
423   return;
424 }
425
426 /* Handle JSON with Bridge table initial values */
427 static void ovs_stats_bridge_table_result_cb(yajl_val jresult,
428                                              yajl_val jerror) {
429   if (YAJL_IS_NULL(jerror))
430     ovs_stats_bridge_table_change_cb(jresult);
431   else
432     ERROR("%s: Error received from OvSDB. Table: Bridge", plugin_name);
433   return;
434 }
435
436 /* Update port name */
437 static int ovs_stats_update_port(const char *uuid, yajl_val port) {
438   const char *new[] = {"new", NULL};
439   const char *name[] = {"name", NULL};
440   yajl_val row;
441   port_list_t *portentry = NULL;
442   if (port && YAJL_IS_OBJECT(port)) {
443     row = yajl_tree_get(port, new, yajl_t_object);
444     if (row && YAJL_IS_OBJECT(row)) {
445       yajl_val port_name = yajl_tree_get(row, name, yajl_t_string);
446       if (port_name && YAJL_IS_STRING(port_name)) {
447         portentry = ovs_stats_get_port(uuid);
448         if (portentry == NULL)
449           portentry = ovs_stats_new_port(NULL, uuid);
450         if (portentry) {
451           pthread_mutex_lock(&g_stats_lock);
452           sstrncpy(portentry->name, YAJL_GET_STRING(port_name),
453                    sizeof(portentry->name));
454           pthread_mutex_unlock(&g_stats_lock);
455         }
456       }
457     }
458   } else {
459     ERROR("Incorrect JSON Port data");
460     return -1;
461   }
462   return 0;
463 }
464
465 /* Delete port from global port list */
466 static int ovs_stats_del_port(const char *uuid) {
467   port_list_t *prev_port = g_port_list_head;
468   for (port_list_t *port = g_port_list_head; port != NULL;
469        prev_port = port, port = port->next) {
470     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0) {
471       if (port == g_port_list_head)
472         g_port_list_head = port->next;
473       else
474         prev_port->next = port->next;
475       sfree(port);
476       break;
477     }
478   }
479   return 0;
480 }
481
482 /* Handle JSON with Port Table change event */
483 static void ovs_stats_port_table_change_cb(yajl_val jupdates) {
484   /* Port Table update example JSON data
485     {
486       "Port": {
487         "ab107d6f-28a1-4257-b1cc-5b742821db8a": {
488           "new": {
489             "name": "br1",
490             "interfaces": [
491               "uuid",
492               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
493             ]
494           }
495         }
496       }
497     }
498    */
499   const char *path[] = {"Port", NULL};
500   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
501   yajl_val port;
502   if (ports && YAJL_IS_OBJECT(ports)) {
503     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
504       port = YAJL_GET_OBJECT(ports)->values[i];
505       ovs_stats_update_port(YAJL_GET_OBJECT(ports)->keys[i], port);
506     }
507   }
508   return;
509 }
510
511 /* Handle JSON with Port table initial values */
512 static void ovs_stats_port_table_result_cb(yajl_val jresult, yajl_val jerror) {
513   if (YAJL_IS_NULL(jerror))
514     ovs_stats_port_table_change_cb(jresult);
515   else
516     ERROR("%s: Error received from OvSDB. Table: Port", plugin_name);
517   return;
518 }
519
520 /* Handle Port Table delete event */
521 static void ovs_stats_port_table_delete_cb(yajl_val jupdates) {
522   const char *path[] = {"Port", NULL};
523   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
524   pthread_mutex_lock(&g_stats_lock);
525   if (ports && YAJL_IS_OBJECT(ports))
526     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
527       ovs_stats_del_port(YAJL_GET_OBJECT(ports)->keys[i]);
528     }
529   pthread_mutex_unlock(&g_stats_lock);
530   return;
531 }
532
533 /* Update interface statistics */
534 static int ovs_stats_update_iface_stats(port_list_t *port, yajl_val stats) {
535   yajl_val stat;
536   iface_counter counter_index = 0;
537   char *counter_name = NULL;
538   int64_t counter_value = 0;
539   if (stats && YAJL_IS_ARRAY(stats))
540     for (size_t i = 0; i < YAJL_GET_ARRAY(stats)->len; i++) {
541       stat = YAJL_GET_ARRAY(stats)->values[i];
542       if (!YAJL_IS_ARRAY(stat))
543         return -1;
544       counter_name = YAJL_GET_STRING(YAJL_GET_ARRAY(stat)->values[0]);
545       counter_index = ovs_stats_counter_name_to_type(counter_name);
546       counter_value = YAJL_GET_INTEGER(YAJL_GET_ARRAY(stat)->values[1]);
547       if (counter_index == not_supported)
548         continue;
549       port->stats[counter_index] = counter_value;
550     }
551
552   return 0;
553 }
554
555 /* Update interface external_ids */
556 static int ovs_stats_update_iface_ext_ids(port_list_t *port, yajl_val ext_ids) {
557   yajl_val ext_id;
558   char *key;
559   char *value;
560
561   if (ext_ids && YAJL_IS_ARRAY(ext_ids))
562     for (size_t i = 0; i < YAJL_GET_ARRAY(ext_ids)->len; i++) {
563       ext_id = YAJL_GET_ARRAY(ext_ids)->values[i];
564       if (!YAJL_IS_ARRAY(ext_id))
565         return -1;
566       key = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[0]);
567       value = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[1]);
568       if (key && value) {
569         if (strncmp(key, "iface-id", strlen(key)) == 0)
570           sstrncpy(port->ex_iface_id, value, sizeof(port->ex_iface_id));
571         else if (strncmp(key, "vm-uuid", strlen(key)) == 0)
572           sstrncpy(port->ex_vm_id, value, sizeof(port->ex_vm_id));
573       }
574     }
575
576   return 0;
577 }
578
579 /* Get interface statistic and external_ids */
580 static int ovs_stats_update_iface(yajl_val iface) {
581   yajl_val row;
582   port_list_t *port = NULL;
583   if (iface && YAJL_IS_OBJECT(iface)) {
584     row = ovs_utils_get_value_by_key(iface, "new");
585     if (row && YAJL_IS_OBJECT(row)) {
586       yajl_val iface_name = ovs_utils_get_value_by_key(row, "name");
587       yajl_val iface_stats = ovs_utils_get_value_by_key(row, "statistics");
588       yajl_val iface_ext_ids = ovs_utils_get_value_by_key(row, "external_ids");
589       yajl_val iface_uuid = ovs_utils_get_value_by_key(row, "_uuid");
590       if (iface_name && YAJL_IS_STRING(iface_name)) {
591         port = ovs_stats_get_port_by_name(YAJL_GET_STRING(iface_name));
592         if (port == NULL)
593           return 0;
594       }
595       /*
596        * {
597             "statistics": [
598               "map",
599               [
600                 [
601                   "collisions",
602                   0
603                 ],
604                 . . .
605                 [
606                   "tx_packets",
607                   0
608                 ]
609               ]
610             ]
611           }
612        Check that statistics is an array with 2 elements
613        */
614       if (iface_stats && YAJL_IS_ARRAY(iface_stats) &&
615           YAJL_GET_ARRAY(iface_stats)->len == 2)
616         ovs_stats_update_iface_stats(port,
617                                      YAJL_GET_ARRAY(iface_stats)->values[1]);
618       if (iface_ext_ids && YAJL_IS_ARRAY(iface_ext_ids))
619         ovs_stats_update_iface_ext_ids(
620             port, YAJL_GET_ARRAY(iface_ext_ids)->values[1]);
621       if (iface_uuid && YAJL_IS_ARRAY(iface_uuid) &&
622           YAJL_GET_ARRAY(iface_uuid)->len == 2)
623         sstrncpy(port->iface_uuid,
624                  YAJL_GET_STRING(YAJL_GET_ARRAY(iface_uuid)->values[1]),
625                  sizeof(port->iface_uuid));
626     }
627   } else {
628     ERROR("Incorrect JSON Port data");
629     return -1;
630   }
631   return 0;
632 }
633
634 /* Handle JSON with Interface Table change event */
635 static void ovs_stats_interface_table_change_cb(yajl_val jupdates) {
636   /* Interface Table update example JSON data
637     {
638       "Interface": {
639         "33a289a0-1d34-4e46-a3c2-3e4066fbecc6": {
640           "new": {
641             "name": "br1",
642             "statistics": [
643               "map",
644               [
645                 [
646                   "collisions",
647                   0
648                 ],
649                 [
650                   "rx_bytes",
651                   0
652                 ],
653                . . .
654                 [
655                   "tx_packets",
656                   12617
657                 ]
658               ]
659             ],
660             "_uuid": [
661               "uuid",
662               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
663             ]
664             "external_ids": [
665                 "map",
666                 [
667                   [
668                     "attached-mac",
669                     "fa:16:3e:7c:1c:4b"
670                   ],
671                   [
672                     "iface-id",
673                     "a61b7e2b-6951-488a-b4c6-6e91343960b2"
674                   ],
675                   [
676                     "iface-status",
677                     "active"
678                   ]
679                 ]
680               ]
681           }
682         }
683       }
684     }
685    */
686   const char *path[] = {"Interface", NULL};
687   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
688   pthread_mutex_lock(&g_stats_lock);
689   if (ports && YAJL_IS_OBJECT(ports))
690     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++)
691       ovs_stats_update_iface(YAJL_GET_OBJECT(ports)->values[i]);
692   pthread_mutex_unlock(&g_stats_lock);
693   return;
694 }
695
696 /* Handle JSON with Interface table initial values */
697 static void ovs_stats_interface_table_result_cb(yajl_val jresult,
698                                                 yajl_val jerror) {
699   if (YAJL_IS_NULL(jerror))
700     ovs_stats_interface_table_change_cb(jresult);
701   else
702     ERROR("%s: Error received from OvSDB. Table: Interface", plugin_name);
703   return;
704 }
705
706 /* Setup OVS DB table callbacks  */
707 static void ovs_stats_initialize(ovs_db_t *pdb) {
708   const char *bridge_columns[] = {"name", "ports", NULL};
709   const char *port_columns[] = {"name", "interfaces", NULL};
710   const char *interface_columns[] = {"name", "statistics", "_uuid",
711                                      "external_ids", NULL};
712
713   /* subscribe to a tables */
714   ovs_db_table_cb_register(pdb, "Bridge", bridge_columns,
715                            ovs_stats_bridge_table_change_cb,
716       ovs_stats_bridge_table_result_cb,
717                            OVS_DB_TABLE_CB_FLAG_INITIAL |
718                            OVS_DB_TABLE_CB_FLAG_INSERT |
719           OVS_DB_TABLE_CB_FLAG_MODIFY);
720
721   ovs_db_table_cb_register(pdb, "Bridge", bridge_columns,
722                            ovs_stats_bridge_table_delete_cb, NULL,
723                            OVS_DB_TABLE_CB_FLAG_DELETE);
724
725   ovs_db_table_cb_register(pdb, "Port", port_columns,
726                            ovs_stats_port_table_change_cb,
727       ovs_stats_port_table_result_cb,
728                            OVS_DB_TABLE_CB_FLAG_INITIAL |
729                            OVS_DB_TABLE_CB_FLAG_INSERT |
730           OVS_DB_TABLE_CB_FLAG_MODIFY);
731
732   ovs_db_table_cb_register(pdb, "Port", port_columns,
733                            ovs_stats_port_table_delete_cb, NULL,
734                            OVS_DB_TABLE_CB_FLAG_DELETE);
735
736   ovs_db_table_cb_register(pdb, "Interface", interface_columns,
737                            ovs_stats_interface_table_change_cb,
738       ovs_stats_interface_table_result_cb,
739                            OVS_DB_TABLE_CB_FLAG_INITIAL |
740                            OVS_DB_TABLE_CB_FLAG_INSERT |
741           OVS_DB_TABLE_CB_FLAG_MODIFY);
742 }
743
744 /* Check if bridge is configured to be monitored in config file */
745 static int ovs_stats_is_monitored_bridge(const char *br_name) {
746   /* if no bridges are configured, return true */
747   if (g_monitored_bridge_list_head == NULL)
748     return 1;
749
750   /* check if given bridge exists */
751   if (ovs_stats_get_bridge(g_monitored_bridge_list_head, br_name) != NULL)
752     return 1;
753
754   return 0;
755 }
756
757 /* Delete all ports from port list */
758 static void ovs_stats_free_port_list(port_list_t *head) {
759   for (port_list_t *i = head; i != NULL;) {
760     port_list_t *del = i;
761     i = i->next;
762     sfree(del);
763   }
764 }
765
766 /* Delete all bridges from bridge list */
767 static void ovs_stats_free_bridge_list(bridge_list_t *head) {
768   for (bridge_list_t *i = head; i != NULL;) {
769     bridge_list_t *del = i;
770     i = i->next;
771     sfree(del->name);
772     sfree(del);
773   }
774 }
775
776 /* Handle OVSDB lost connection callback */
777 static void ovs_stats_conn_terminate() {
778   WARNING("Lost connection to OVSDB server");
779   pthread_mutex_lock(&g_stats_lock);
780   ovs_stats_free_bridge_list(g_bridge_list_head);
781   g_bridge_list_head = NULL;
782   ovs_stats_free_port_list(g_port_list_head);
783   g_port_list_head = NULL;
784   pthread_mutex_unlock(&g_stats_lock);
785 }
786
787 /* Parse plugin configuration file and store the config
788  * in allocated memory. Returns negative value in case of error.
789  */
790 static int ovs_stats_plugin_config(oconfig_item_t *ci) {
791   bridge_list_t *bridge;
792   char *br_name;
793
794   for (int i = 0; i < ci->children_num; i++) {
795     oconfig_item_t *child = ci->children + i;
796     if (strcasecmp("Address", child->key) == 0) {
797       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_node,
798                                     OVS_DB_ADDR_NODE_SIZE) != 0) {
799         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
800         return -1;
801       }
802     } else if (strcasecmp("Port", child->key) == 0) {
803       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_serv,
804                                     OVS_DB_ADDR_SERVICE_SIZE) != 0) {
805         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
806         return -1;
807       }
808     } else if (strcasecmp("Socket", child->key) == 0) {
809       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_unix,
810                                     OVS_DB_ADDR_UNIX_SIZE) != 0) {
811         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
812         return -1;
813       }
814     } else if (strcasecmp("Bridges", child->key) == 0) {
815       for (int j = 0; j < child->values_num; j++) {
816         /* check value type */
817         if (child->values[j].type != OCONFIG_TYPE_STRING) {
818           ERROR("%s: Wrong bridge name [idx=%d]. "
819                 "Bridge name should be string",
820                 plugin_name, j);
821           goto cleanup_fail;
822         }
823         /* get value */
824         if ((br_name = strdup(child->values[j].value.string)) == NULL) {
825           ERROR("%s: strdup() copy bridge name fail", plugin_name);
826           goto cleanup_fail;
827         }
828         if ((bridge = ovs_stats_get_bridge(g_monitored_bridge_list_head,
829                                            br_name)) == NULL) {
830           if ((bridge = calloc(1, sizeof(bridge_list_t))) == NULL) {
831             ERROR("%s: Error allocating memory for bridge", plugin_name);
832             goto cleanup_fail;
833           } else {
834             pthread_mutex_lock(&g_stats_lock);
835             /* store bridge name */
836             bridge->name = br_name;
837             bridge->next = g_monitored_bridge_list_head;
838             g_monitored_bridge_list_head = bridge;
839             pthread_mutex_unlock(&g_stats_lock);
840             DEBUG("%s: found monitored interface \"%s\"", plugin_name, br_name);
841           }
842         }
843       }
844     } else {
845       WARNING("%s: option '%s' not allowed here", plugin_name, child->key);
846       goto cleanup_fail;
847     }
848   }
849   return 0;
850
851 cleanup_fail:
852   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
853   return -1;
854 }
855
856 /* Initialize OvS Stats plugin*/
857 static int ovs_stats_plugin_init(void) {
858   ovs_db_callback_t cb = {.post_conn_init = ovs_stats_initialize,
859                           .post_conn_terminate = ovs_stats_conn_terminate};
860
861   INFO("%s: Connecting to OVS DB using address=%s, service=%s, unix=%s",
862        plugin_name, ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
863        ovs_stats_cfg.ovs_db_unix);
864   /* connect to OvS DB */
865   if ((g_ovs_db = ovs_db_init (ovs_stats_cfg.ovs_db_node,
866                              ovs_stats_cfg.ovs_db_serv,
867                        ovs_stats_cfg.ovs_db_unix, &cb)) == NULL) {
868     ERROR("%s: plugin: failed to connect to OvS DB server", plugin_name);
869     return -1;
870   }
871   int err = pthread_mutex_init(&g_stats_lock, NULL);
872   if (err < 0) {
873     ERROR("%s: plugin: failed to initialize cache lock", plugin_name);
874     ovs_db_destroy(g_ovs_db);
875     return -1;
876   }
877   return 0;
878 }
879
880 /* OvS stats read callback. Read bridge/port information and submit it*/
881 static int ovs_stats_plugin_read(__attribute__((unused)) user_data_t *ud) {
882   bridge_list_t *bridge;
883   port_list_t *port;
884   char devname[PORT_NAME_SIZE_MAX * 2];
885
886   pthread_mutex_lock(&g_stats_lock);
887   for (bridge = g_bridge_list_head; bridge != NULL; bridge = bridge->next) {
888     if (ovs_stats_is_monitored_bridge(bridge->name)) {
889       for (port = g_port_list_head; port != NULL; port = port->next)
890         if (port->br == bridge) {
891           if (strlen(port->name) == 0)
892             /* Skip port w/o name. This is possible when read callback
893              * is called after Interface Table update callback but before
894              * Port table Update callback. Will add this port on next read */
895             continue;
896           meta_data_t *meta = meta_data_create();
897           if (meta != NULL) {
898             meta_data_add_string(meta, "uuid", port->iface_uuid);
899             if (strlen(port->ex_vm_id))
900               meta_data_add_string(meta, "vm-uuid", port->ex_vm_id);
901             if (strlen(port->ex_iface_id))
902               meta_data_add_string(meta, "iface-id", port->ex_iface_id);
903           }
904           snprintf(devname, sizeof(devname), "%s.%s", bridge->name, port->name);
905           ovs_stats_submit_one(devname, "if_collisions", NULL,
906                                port->stats[collisions], meta);
907           ovs_stats_submit_two(devname, "if_dropped", NULL,
908                                port->stats[rx_dropped], port->stats[tx_dropped],
909                                meta);
910           ovs_stats_submit_two(devname, "if_errors", NULL,
911                                port->stats[rx_errors], port->stats[tx_errors],
912                                meta);
913           ovs_stats_submit_two(devname, "if_packets", NULL,
914                                port->stats[rx_packets], port->stats[tx_packets],
915                                meta);
916           ovs_stats_submit_one(devname, "if_rx_errors", "crc",
917                                port->stats[rx_crc_err], meta);
918           ovs_stats_submit_one(devname, "if_rx_errors", "frame",
919                                port->stats[rx_frame_err], meta);
920           ovs_stats_submit_one(devname, "if_rx_errors", "over",
921                                port->stats[rx_over_err], meta);
922           ovs_stats_submit_one(devname, "if_rx_octets", NULL,
923                                port->stats[rx_bytes], meta);
924           ovs_stats_submit_one(devname, "if_tx_octets", NULL,
925                                port->stats[tx_bytes], meta);
926           ovs_stats_submit_two(devname, "if_packets", "1_to_64_packets",
927                                port->stats[rx_1_to_64_packets],
928                                port->stats[tx_1_to_64_packets], meta);
929           ovs_stats_submit_two(devname, "if_packets", "65_to_127_packets",
930                                port->stats[rx_65_to_127_packets],
931                                port->stats[tx_65_to_127_packets], meta);
932           ovs_stats_submit_two(devname, "if_packets", "128_to_255_packets",
933                                port->stats[rx_128_to_255_packets],
934                                port->stats[tx_128_to_255_packets], meta);
935           ovs_stats_submit_two(devname, "if_packets", "256_to_511_packets",
936                                port->stats[rx_256_to_511_packets],
937                                port->stats[tx_256_to_511_packets], meta);
938           ovs_stats_submit_two(devname, "if_packets", "512_to_1023_packets",
939                                port->stats[rx_512_to_1023_packets],
940                                port->stats[tx_512_to_1023_packets], meta);
941           ovs_stats_submit_two(devname, "if_packets", "1024_to_1518_packets",
942                                port->stats[rx_1024_to_1522_packets],
943                                port->stats[tx_1024_to_1522_packets], meta);
944           ovs_stats_submit_two(devname, "if_packets", "1523_to_max_packets",
945                                port->stats[rx_1523_to_max_packets],
946                                port->stats[tx_1523_to_max_packets], meta);
947           ovs_stats_submit_two(devname, "if_packets", "broadcast_packets",
948                                port->stats[rx_broadcast_packets],
949                                port->stats[tx_broadcast_packets], meta);
950           ovs_stats_submit_one(devname, "if_multicast", "tx_multicast_packets",
951                                port->stats[tx_multicast_packets], meta);
952           ovs_stats_submit_one(devname, "if_rx_errors", "rx_undersized_errors",
953                                port->stats[rx_undersized_errors], meta);
954           ovs_stats_submit_one(devname, "if_rx_errors", "rx_oversize_errors",
955                                port->stats[rx_oversize_errors], meta);
956           ovs_stats_submit_one(devname, "if_rx_errors", "rx_fragmented_errors",
957                                port->stats[rx_fragmented_errors], meta);
958           ovs_stats_submit_one(devname, "if_rx_errors", "rx_jabber_errors",
959                                port->stats[rx_jabber_errors], meta);
960
961           meta_data_destroy(meta);
962         }
963     } else
964       continue;
965   }
966   pthread_mutex_unlock(&g_stats_lock);
967   return 0;
968 }
969
970 /* Shutdown OvS Stats plugin */
971 static int ovs_stats_plugin_shutdown(void) {
972   pthread_mutex_lock(&g_stats_lock);
973   DEBUG("OvS Statistics plugin shutting down");
974   ovs_db_destroy(g_ovs_db);
975   ovs_stats_free_bridge_list(g_bridge_list_head);
976   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
977   ovs_stats_free_port_list(g_port_list_head);
978   pthread_mutex_unlock(&g_stats_lock);
979   pthread_mutex_destroy(&g_stats_lock);
980   return 0;
981 }
982
983 /* Register OvS Stats plugin callbacks */
984 void module_register(void) {
985   plugin_register_complex_config(plugin_name, ovs_stats_plugin_config);
986   plugin_register_init(plugin_name, ovs_stats_plugin_init);
987   plugin_register_complex_read(NULL, plugin_name, ovs_stats_plugin_read, 0,
988                                NULL);
989   plugin_register_shutdown(plugin_name, ovs_stats_plugin_shutdown);
990 }