Document InterfaceStats option for ovs_stats plugin
[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
7  * of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
11  * of the Software, and to permit persons to whom the Software is furnished to
12  * do
13  * so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all
17  * copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  *
27  * Authors:
28  *   Taras Chornyi <tarasx.chornyi@intel.com>
29  */
30
31 #include "common.h"
32
33 #include "utils_ovs.h" /* OvS helpers */
34
35 /* Plugin name */
36 static const char plugin_name[] = "ovs_stats";
37
38 typedef enum iface_counter {
39   not_supported = -1,
40   collisions,
41   rx_bytes,
42   rx_crc_err,
43   rx_dropped,
44   rx_errors,
45   rx_frame_err,
46   rx_over_err,
47   rx_packets,
48   tx_bytes,
49   tx_dropped,
50   tx_errors,
51   tx_packets,
52   rx_1_to_64_packets,
53   rx_65_to_127_packets,
54   rx_128_to_255_packets,
55   rx_256_to_511_packets,
56   rx_512_to_1023_packets,
57   rx_1024_to_1522_packets,
58   rx_1523_to_max_packets,
59   tx_1_to_64_packets,
60   tx_65_to_127_packets,
61   tx_128_to_255_packets,
62   tx_256_to_511_packets,
63   tx_512_to_1023_packets,
64   tx_1024_to_1522_packets,
65   tx_1523_to_max_packets,
66   tx_multicast_packets,
67   rx_broadcast_packets,
68   tx_broadcast_packets,
69   rx_undersized_errors,
70   rx_oversize_errors,
71   rx_fragmented_errors,
72   rx_jabber_errors,
73   __iface_counter_max
74 } iface_counter;
75
76 #define IFACE_COUNTER_MAX (__iface_counter_max - 1)
77 #define IFACE_COUNTER_COUNT (__iface_counter_max)
78 #define PORT_NAME_SIZE_MAX 255
79 #define UUID_SIZE 64
80
81 typedef struct interface_s {
82   char name[PORT_NAME_SIZE_MAX];      /* Interface name */
83   char port_uuid[UUID_SIZE];          /* Port table _uuid */
84   char iface_uuid[UUID_SIZE];         /* Interface table uuid */
85   char ex_iface_id[UUID_SIZE];        /* External iface id */
86   char ex_vm_id[UUID_SIZE];           /* External vm id */
87   int64_t stats[IFACE_COUNTER_COUNT]; /* Statistics for interface */
88   struct interface_s *next;           /* Next interface for associated port */
89 } interface_list_t;
90
91 typedef struct port_s {
92   char name[PORT_NAME_SIZE_MAX]; /* Port name */
93   char port_uuid[UUID_SIZE];     /* Port table _uuid */
94   struct bridge_list_s *br;      /* Pointer to bridge */
95   struct interface_s *iface;     /* Pointer to first interface */
96   struct port_s *next;           /* Next port */
97 } port_list_t;
98
99 typedef struct bridge_list_s {
100   char *name;                 /* Bridge name */
101   struct bridge_list_s *next; /* Next bridge*/
102 } bridge_list_t;
103
104 static const char *const iface_counter_table[IFACE_COUNTER_COUNT] = {
105         [collisions] = "collisions",
106         [rx_bytes] = "rx_bytes",
107         [rx_crc_err] = "rx_crc_err",
108         [rx_dropped] = "rx_dropped",
109         [rx_errors] = "rx_errors",
110         [rx_frame_err] = "rx_frame_err",
111         [rx_over_err] = "rx_over_err",
112         [rx_packets] = "rx_packets",
113         [tx_bytes] = "tx_bytes",
114         [tx_dropped] = "tx_dropped",
115         [tx_errors] = "tx_errors",
116         [tx_packets] = "tx_packets",
117         [rx_1_to_64_packets] = "rx_1_to_64_packets",
118         [rx_65_to_127_packets] = "rx_65_to_127_packets",
119         [rx_128_to_255_packets] = "rx_128_to_255_packets",
120         [rx_256_to_511_packets] = "rx_256_to_511_packets",
121         [rx_512_to_1023_packets] = "rx_512_to_1023_packets",
122         [rx_1024_to_1522_packets] = "rx_1024_to_1518_packets",
123         [rx_1523_to_max_packets] = "rx_1523_to_max_packets",
124         [tx_1_to_64_packets] = "tx_1_to_64_packets",
125         [tx_65_to_127_packets] = "tx_65_to_127_packets",
126         [tx_128_to_255_packets] = "tx_128_to_255_packets",
127         [tx_256_to_511_packets] = "tx_256_to_511_packets",
128         [tx_512_to_1023_packets] = "tx_512_to_1023_packets",
129         [tx_1024_to_1522_packets] = "tx_1024_to_1518_packets",
130         [tx_1523_to_max_packets] = "tx_1523_to_max_packets",
131         [tx_multicast_packets] = "tx_multicast_packets",
132         [rx_broadcast_packets] = "rx_broadcast_packets",
133         [tx_broadcast_packets] = "tx_broadcast_packets",
134         [rx_undersized_errors] = "rx_undersized_errors",
135         [rx_oversize_errors] = "rx_oversize_errors",
136         [rx_fragmented_errors] = "rx_fragmented_errors",
137         [rx_jabber_errors] = "rx_jabber_errors",
138 };
139
140 /* Entry into the list of network bridges */
141 static bridge_list_t *g_bridge_list_head;
142
143 /* Entry into the list of monitored network bridges */
144 static bridge_list_t *g_monitored_bridge_list_head;
145
146 /* entry into the list of network bridges */
147 static port_list_t *g_port_list_head;
148
149 /* lock for statistics cache */
150 static pthread_mutex_t g_stats_lock;
151
152 /* OvS DB socket */
153 static ovs_db_t *g_ovs_db;
154
155 /* OVS stats configuration data */
156 struct ovs_stats_config_s {
157   char ovs_db_node[OVS_DB_ADDR_NODE_SIZE];    /* OVS DB node */
158   char ovs_db_serv[OVS_DB_ADDR_SERVICE_SIZE]; /* OVS DB service */
159   char ovs_db_unix[OVS_DB_ADDR_UNIX_SIZE];    /* OVS DB unix socket path */
160 };
161 typedef struct ovs_stats_config_s ovs_stats_config_t;
162
163 static ovs_stats_config_t ovs_stats_cfg = {
164     .ovs_db_node = "localhost", /* use default OVS DB node */
165     .ovs_db_serv = "6640",      /* use default OVS DB service */
166 };
167
168 /* flag indicating whether or not to publish individual interface statistics */
169 static bool interface_stats = false;
170
171 static iface_counter ovs_stats_counter_name_to_type(const char *counter) {
172   iface_counter index = not_supported;
173
174   if (counter == NULL)
175     return not_supported;
176
177   for (int i = 0; i < IFACE_COUNTER_COUNT; i++) {
178     if (strncmp(iface_counter_table[i], counter,
179                 strlen(iface_counter_table[i])) == 0) {
180       index = i;
181       break;
182     }
183   }
184   return index;
185 }
186
187 static void ovs_stats_submit_one(const char *dev, const char *type,
188                                  const char *type_instance, derive_t value,
189                                  meta_data_t *meta) {
190   /* if counter is less than 0 - skip it*/
191   if (value < 0)
192     return;
193   value_list_t vl = VALUE_LIST_INIT;
194
195   vl.values = &(value_t){.derive = value};
196   vl.values_len = 1;
197   vl.meta = meta;
198
199   sstrncpy(vl.plugin, plugin_name, sizeof(vl.plugin));
200   sstrncpy(vl.plugin_instance, dev, sizeof(vl.plugin_instance));
201   sstrncpy(vl.type, type, sizeof(vl.type));
202
203   if (type_instance != NULL)
204     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
205
206   plugin_dispatch_values(&vl);
207 }
208
209 static void ovs_stats_submit_two(const char *dev, const char *type,
210                                  const char *type_instance, derive_t rx,
211                                  derive_t tx, meta_data_t *meta) {
212   /* if counter is less than 0 - skip it*/
213   if (rx < 0 || tx < 0)
214     return;
215   value_list_t vl = VALUE_LIST_INIT;
216   value_t values[] = {{.derive = rx}, {.derive = tx}};
217
218   vl.values = values;
219   vl.values_len = STATIC_ARRAY_SIZE(values);
220   vl.meta = meta;
221
222   sstrncpy(vl.plugin, plugin_name, sizeof(vl.plugin));
223   sstrncpy(vl.plugin_instance, dev, sizeof(vl.plugin_instance));
224   sstrncpy(vl.type, type, sizeof(vl.type));
225
226   if (type_instance != NULL)
227     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
228
229   plugin_dispatch_values(&vl);
230 }
231
232 static void ovs_stats_submit_interfaces(bridge_list_t *bridge,
233                                         port_list_t *port) {
234   char devname[PORT_NAME_SIZE_MAX * 2];
235
236   for (interface_list_t *iface = port->iface; iface != NULL;
237        iface = iface->next) {
238     meta_data_t *meta = meta_data_create();
239     if (meta != NULL) {
240       meta_data_add_string(meta, "uuid", iface->iface_uuid);
241
242       if (strlen(iface->ex_vm_id))
243         meta_data_add_string(meta, "vm-uuid", iface->ex_vm_id);
244
245       if (strlen(iface->ex_iface_id))
246         meta_data_add_string(meta, "iface-id", iface->ex_iface_id);
247     }
248     snprintf(devname, sizeof(devname), "%s.%s.%s", bridge->name, port->name,
249              iface->name);
250     ovs_stats_submit_one(devname, "if_collisions", NULL,
251                          iface->stats[collisions], meta);
252     ovs_stats_submit_two(devname, "if_dropped", NULL, iface->stats[rx_dropped],
253                          iface->stats[tx_dropped], meta);
254     ovs_stats_submit_two(devname, "if_errors", NULL, iface->stats[rx_errors],
255                          iface->stats[tx_errors], meta);
256     ovs_stats_submit_two(devname, "if_packets", NULL, iface->stats[rx_packets],
257                          iface->stats[tx_packets], meta);
258     ovs_stats_submit_one(devname, "if_rx_errors", "crc",
259                          iface->stats[rx_crc_err], meta);
260     ovs_stats_submit_one(devname, "if_rx_errors", "frame",
261                          iface->stats[rx_frame_err], meta);
262     ovs_stats_submit_one(devname, "if_rx_errors", "over",
263                          iface->stats[rx_over_err], meta);
264     ovs_stats_submit_one(devname, "if_rx_octets", NULL, iface->stats[rx_bytes],
265                          meta);
266     ovs_stats_submit_one(devname, "if_tx_octets", NULL, iface->stats[tx_bytes],
267                          meta);
268     ovs_stats_submit_two(devname, "if_packets", "1_to_64_packets",
269                          iface->stats[rx_1_to_64_packets],
270                          iface->stats[tx_1_to_64_packets], meta);
271     ovs_stats_submit_two(devname, "if_packets", "65_to_127_packets",
272                          iface->stats[rx_65_to_127_packets],
273                          iface->stats[tx_65_to_127_packets], meta);
274     ovs_stats_submit_two(devname, "if_packets", "128_to_255_packets",
275                          iface->stats[rx_128_to_255_packets],
276                          iface->stats[tx_128_to_255_packets], meta);
277     ovs_stats_submit_two(devname, "if_packets", "256_to_511_packets",
278                          iface->stats[rx_256_to_511_packets],
279                          iface->stats[tx_256_to_511_packets], meta);
280     ovs_stats_submit_two(devname, "if_packets", "512_to_1023_packets",
281                          iface->stats[rx_512_to_1023_packets],
282                          iface->stats[tx_512_to_1023_packets], meta);
283     ovs_stats_submit_two(devname, "if_packets", "1024_to_1518_packets",
284                          iface->stats[rx_1024_to_1522_packets],
285                          iface->stats[tx_1024_to_1522_packets], meta);
286     ovs_stats_submit_two(devname, "if_packets", "1523_to_max_packets",
287                          iface->stats[rx_1523_to_max_packets],
288                          iface->stats[tx_1523_to_max_packets], meta);
289     ovs_stats_submit_two(devname, "if_packets", "broadcast_packets",
290                          iface->stats[rx_broadcast_packets],
291                          iface->stats[tx_broadcast_packets], meta);
292     ovs_stats_submit_one(devname, "if_multicast", "tx_multicast_packets",
293                          iface->stats[tx_multicast_packets], meta);
294     ovs_stats_submit_one(devname, "if_rx_errors", "rx_undersized_errors",
295                          iface->stats[rx_undersized_errors], meta);
296     ovs_stats_submit_one(devname, "if_rx_errors", "rx_oversize_errors",
297                          iface->stats[rx_oversize_errors], meta);
298     ovs_stats_submit_one(devname, "if_rx_errors", "rx_fragmented_errors",
299                          iface->stats[rx_fragmented_errors], meta);
300     ovs_stats_submit_one(devname, "if_rx_errors", "rx_jabber_errors",
301                          iface->stats[rx_jabber_errors], meta);
302
303     meta_data_destroy(meta);
304   }
305 }
306
307 static int ovs_stats_get_port_stat_value(port_list_t *port,
308                                          iface_counter index) {
309   if (port == NULL)
310     return 0;
311
312   int value = 0;
313
314   for (interface_list_t *iface = port->iface; iface != NULL;
315        iface = iface->next) {
316     value = value + iface->stats[index];
317   }
318
319   return value;
320 }
321
322 static void ovs_stats_submit_port(bridge_list_t *bridge, port_list_t *port) {
323   char devname[PORT_NAME_SIZE_MAX * 2];
324
325   meta_data_t *meta = meta_data_create();
326   if (meta != NULL) {
327     char key_str[DATA_MAX_NAME_LEN];
328     int i = 0;
329
330     for (interface_list_t *iface = port->iface; iface != NULL;
331          iface = iface->next) {
332       memset(key_str, '\0', DATA_MAX_NAME_LEN);
333       snprintf(key_str, 6, "uuid%d", i);
334       meta_data_add_string(meta, key_str, iface->iface_uuid);
335
336       if (strlen(iface->ex_vm_id)) {
337         memset(key_str, '\0', DATA_MAX_NAME_LEN);
338         snprintf(key_str, 9, "vm-uuid%d", i);
339         meta_data_add_string(meta, key_str, iface->ex_vm_id);
340       }
341
342       if (strlen(iface->ex_iface_id)) {
343         memset(key_str, '\0', DATA_MAX_NAME_LEN);
344         snprintf(key_str, 10, "iface-id%d", i);
345         meta_data_add_string(meta, key_str, iface->ex_iface_id);
346       }
347
348       i++;
349     }
350   }
351   snprintf(devname, sizeof(devname), "%s.%s", bridge->name, port->name);
352   ovs_stats_submit_one(devname, "if_collisions", NULL,
353                        ovs_stats_get_port_stat_value(port, collisions), meta);
354   ovs_stats_submit_two(devname, "if_dropped", NULL,
355                        ovs_stats_get_port_stat_value(port, rx_dropped),
356                        ovs_stats_get_port_stat_value(port, tx_dropped), meta);
357   ovs_stats_submit_two(devname, "if_errors", NULL,
358                        ovs_stats_get_port_stat_value(port, rx_errors),
359                        ovs_stats_get_port_stat_value(port, tx_errors), meta);
360   ovs_stats_submit_two(devname, "if_packets", NULL,
361                        ovs_stats_get_port_stat_value(port, rx_packets),
362                        ovs_stats_get_port_stat_value(port, tx_packets), meta);
363   ovs_stats_submit_one(devname, "if_rx_errors", "crc",
364                        ovs_stats_get_port_stat_value(port, rx_crc_err), meta);
365   ovs_stats_submit_one(devname, "if_rx_errors", "frame",
366                        ovs_stats_get_port_stat_value(port, rx_frame_err), meta);
367   ovs_stats_submit_one(devname, "if_rx_errors", "over",
368                        ovs_stats_get_port_stat_value(port, rx_over_err), meta);
369   ovs_stats_submit_one(devname, "if_rx_octets", NULL,
370                        ovs_stats_get_port_stat_value(port, rx_bytes), meta);
371   ovs_stats_submit_one(devname, "if_tx_octets", NULL,
372                        ovs_stats_get_port_stat_value(port, tx_bytes), meta);
373   ovs_stats_submit_two(devname, "if_packets", "1_to_64_packets",
374                        ovs_stats_get_port_stat_value(port, rx_1_to_64_packets),
375                        ovs_stats_get_port_stat_value(port, tx_1_to_64_packets),
376                        meta);
377   ovs_stats_submit_two(
378       devname, "if_packets", "65_to_127_packets",
379       ovs_stats_get_port_stat_value(port, rx_65_to_127_packets),
380       ovs_stats_get_port_stat_value(port, tx_65_to_127_packets), meta);
381   ovs_stats_submit_two(
382       devname, "if_packets", "128_to_255_packets",
383       ovs_stats_get_port_stat_value(port, rx_128_to_255_packets),
384       ovs_stats_get_port_stat_value(port, tx_128_to_255_packets), meta);
385   ovs_stats_submit_two(
386       devname, "if_packets", "256_to_511_packets",
387       ovs_stats_get_port_stat_value(port, rx_256_to_511_packets),
388       ovs_stats_get_port_stat_value(port, tx_256_to_511_packets), meta);
389   ovs_stats_submit_two(
390       devname, "if_packets", "512_to_1023_packets",
391       ovs_stats_get_port_stat_value(port, rx_512_to_1023_packets),
392       ovs_stats_get_port_stat_value(port, tx_512_to_1023_packets), meta);
393   ovs_stats_submit_two(
394       devname, "if_packets", "1024_to_1518_packets",
395       ovs_stats_get_port_stat_value(port, rx_1024_to_1522_packets),
396       ovs_stats_get_port_stat_value(port, tx_1024_to_1522_packets), meta);
397   ovs_stats_submit_two(
398       devname, "if_packets", "1523_to_max_packets",
399       ovs_stats_get_port_stat_value(port, rx_1523_to_max_packets),
400       ovs_stats_get_port_stat_value(port, tx_1523_to_max_packets), meta);
401   ovs_stats_submit_two(
402       devname, "if_packets", "broadcast_packets",
403       ovs_stats_get_port_stat_value(port, rx_broadcast_packets),
404       ovs_stats_get_port_stat_value(port, tx_broadcast_packets), meta);
405   ovs_stats_submit_one(
406       devname, "if_multicast", "tx_multicast_packets",
407       ovs_stats_get_port_stat_value(port, tx_multicast_packets), meta);
408   ovs_stats_submit_one(
409       devname, "if_rx_errors", "rx_undersized_errors",
410       ovs_stats_get_port_stat_value(port, rx_undersized_errors), meta);
411   ovs_stats_submit_one(devname, "if_rx_errors", "rx_oversize_errors",
412                        ovs_stats_get_port_stat_value(port, rx_oversize_errors),
413                        meta);
414   ovs_stats_submit_one(
415       devname, "if_rx_errors", "rx_fragmented_errors",
416       ovs_stats_get_port_stat_value(port, rx_fragmented_errors), meta);
417   ovs_stats_submit_one(devname, "if_rx_errors", "rx_jabber_errors",
418                        ovs_stats_get_port_stat_value(port, rx_jabber_errors),
419                        meta);
420
421   meta_data_destroy(meta);
422 }
423
424 static port_list_t *ovs_stats_get_port(const char *uuid) {
425   if (uuid == NULL)
426     return NULL;
427
428   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
429     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0)
430       return port;
431   }
432   return NULL;
433 }
434
435 static port_list_t *ovs_stats_get_port_by_interface_uuid(const char *uuid) {
436   if (uuid == NULL)
437     return NULL;
438
439   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
440     for (interface_list_t *iface = port->iface; iface != NULL;
441          iface = iface->next) {
442       if (strncmp(iface->iface_uuid, uuid, strlen(uuid)) == 0)
443         return port;
444     }
445   }
446   return NULL;
447 }
448
449 static interface_list_t *ovs_stats_get_port_interface(port_list_t *port,
450                                                       const char *uuid) {
451   if (port == NULL || uuid == NULL)
452     return NULL;
453
454   for (interface_list_t *iface = port->iface; iface != NULL;
455        iface = iface->next) {
456     if (strncmp(iface->iface_uuid, uuid, strlen(uuid)) == 0)
457       return iface;
458   }
459   return NULL;
460 }
461
462 static interface_list_t *ovs_stats_get_interface(const char *uuid) {
463   if (uuid == NULL)
464     return NULL;
465
466   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
467     for (interface_list_t *iface = port->iface; iface != NULL;
468          iface = iface->next) {
469       if (strncmp(iface->iface_uuid, uuid, strlen(uuid)) == 0)
470         return iface;
471     }
472   }
473   return NULL;
474 }
475
476 static interface_list_t *ovs_stats_new_port_interface(port_list_t *port,
477                                                       const char *uuid) {
478   if (uuid == NULL)
479     return NULL;
480
481   interface_list_t *iface = ovs_stats_get_port_interface(port, uuid);
482
483   if (iface == NULL) {
484     iface = (interface_list_t *)calloc(1, sizeof(interface_list_t));
485     if (!iface) {
486       ERROR("%s: Error allocating interface", plugin_name);
487       return NULL;
488     }
489     memset(iface->stats, -1, sizeof(int64_t[IFACE_COUNTER_COUNT]));
490     sstrncpy(iface->iface_uuid, uuid, sizeof(iface->iface_uuid));
491     sstrncpy(iface->port_uuid, port->port_uuid, sizeof(iface->port_uuid));
492     pthread_mutex_lock(&g_stats_lock);
493     interface_list_t *iface_head = port->iface;
494     iface->next = iface_head;
495     port->iface = iface;
496     pthread_mutex_unlock(&g_stats_lock);
497   }
498   return iface;
499 }
500
501 /* Create or get port by port uuid */
502 static port_list_t *ovs_stats_new_port(bridge_list_t *bridge,
503                                        const char *uuid) {
504   if (uuid == NULL)
505     return NULL;
506
507   port_list_t *port = ovs_stats_get_port(uuid);
508
509   if (port == NULL) {
510     port = (port_list_t *)calloc(1, sizeof(port_list_t));
511     if (!port) {
512       ERROR("%s: Error allocating port", plugin_name);
513       return NULL;
514     }
515     sstrncpy(port->port_uuid, uuid, sizeof(port->port_uuid));
516     pthread_mutex_lock(&g_stats_lock);
517     port->next = g_port_list_head;
518     g_port_list_head = port;
519     pthread_mutex_unlock(&g_stats_lock);
520   }
521   if (bridge != NULL) {
522     pthread_mutex_lock(&g_stats_lock);
523     port->br = bridge;
524     pthread_mutex_unlock(&g_stats_lock);
525   }
526   return port;
527 }
528
529 /* Get bridge by name*/
530 static bridge_list_t *ovs_stats_get_bridge(bridge_list_t *head,
531                                            const char *name) {
532   if (name == NULL)
533     return NULL;
534
535   for (bridge_list_t *bridge = head; bridge != NULL; bridge = bridge->next) {
536     if ((strncmp(bridge->name, name, strlen(bridge->name)) == 0) &&
537         strlen(name) == strlen(bridge->name))
538       return bridge;
539   }
540   return NULL;
541 }
542
543 /* Delete bridge */
544 static int ovs_stats_del_bridge(yajl_val bridge) {
545   const char *old[] = {"old", NULL};
546   const char *name[] = {"name", NULL};
547
548   yajl_val row;
549
550   if (bridge && YAJL_IS_OBJECT(bridge)) {
551     row = yajl_tree_get(bridge, old, yajl_t_object);
552     if (row && YAJL_IS_OBJECT(row)) {
553       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
554       if (br_name && YAJL_IS_STRING(br_name)) {
555         bridge_list_t *prev_br = g_bridge_list_head;
556         for (bridge_list_t *br = g_bridge_list_head; br != NULL;
557              prev_br = br, br = br->next) {
558           if ((strncmp(br->name, br_name->u.string, strlen(br->name)) == 0) &&
559               strlen(br->name) == strlen(br_name->u.string)) {
560             if (br == g_bridge_list_head)
561               g_bridge_list_head = br->next;
562             else
563               prev_br->next = br->next;
564             sfree(br->name);
565             sfree(br);
566             break;
567           }
568         }
569       }
570     }
571   } else
572     WARNING("%s: Incorrect data for deleting bridge", plugin_name);
573   return 0;
574 }
575
576 /* Update Bridge. Create bridge ports*/
577 static int ovs_stats_update_bridge(yajl_val bridge) {
578   const char *new[] = {"new", NULL};
579   const char *name[] = {"name", NULL};
580   const char *ports[] = {"ports", NULL};
581   bridge_list_t *br = NULL;
582
583   if (bridge && YAJL_IS_OBJECT(bridge)) {
584     yajl_val row = yajl_tree_get(bridge, new, yajl_t_object);
585     if (row && YAJL_IS_OBJECT(row)) {
586       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
587       yajl_val br_ports = yajl_tree_get(row, ports, yajl_t_array);
588       if (br_name && YAJL_IS_STRING(br_name)) {
589         br = ovs_stats_get_bridge(g_bridge_list_head, YAJL_GET_STRING(br_name));
590         pthread_mutex_lock(&g_stats_lock);
591         if (br == NULL) {
592           br = calloc(1, sizeof(*br));
593           if (!br) {
594             pthread_mutex_unlock(&g_stats_lock);
595             ERROR("%s: calloc(%zu) failed.", plugin_name, sizeof(*br));
596             return -1;
597           }
598           char *tmp = YAJL_GET_STRING(br_name);
599
600           if (tmp != NULL)
601             br->name = strdup(tmp);
602           if (br->name == NULL) {
603             sfree(br);
604             pthread_mutex_unlock(&g_stats_lock);
605             ERROR("%s: strdup failed.", plugin_name);
606             return -1;
607           }
608           br->next = g_bridge_list_head;
609           g_bridge_list_head = br;
610         }
611         pthread_mutex_unlock(&g_stats_lock);
612       }
613       if (br_ports && YAJL_IS_ARRAY(br_ports)) {
614         char *tmp = YAJL_GET_STRING(br_ports->u.array.values[0]);
615         if (tmp != NULL && strcmp("set", tmp) == 0) {
616           yajl_val *array = YAJL_GET_ARRAY(br_ports)->values;
617           size_t array_len = YAJL_GET_ARRAY(br_ports)->len;
618           if (array != NULL && array_len > 0 && YAJL_IS_ARRAY(array[1])) {
619             if (YAJL_GET_ARRAY(array[1]) == NULL)
620               goto failure;
621             else {
622               yajl_val *ports_arr = YAJL_GET_ARRAY(array[1])->values;
623               size_t ports_num = YAJL_GET_ARRAY(array[1])->len;
624               for (size_t i = 0; i < ports_num && ports_arr != NULL; i++) {
625                 tmp = YAJL_GET_STRING(ports_arr[i]->u.array.values[1]);
626                 if (tmp != NULL)
627                   ovs_stats_new_port(br, tmp);
628                 else
629                   goto failure;
630               }
631             }
632           }
633         } else
634           ovs_stats_new_port(br, YAJL_GET_STRING(br_ports->u.array.values[1]));
635       }
636     }
637   } else {
638     goto failure;
639   }
640
641   return 0;
642
643 failure:
644   ERROR("Incorrect JSON Bridge data");
645   return -1;
646 }
647
648 /* Handle JSON with Bridge Table change event */
649 static void ovs_stats_bridge_table_change_cb(yajl_val jupdates) {
650   /* Bridge Table update example JSON data
651     {
652       "Bridge": {
653         "bb1f8965-5775-46d9-b820-236ca8edbedc": {
654           "new": {
655             "name": "br0",
656             "ports": [
657               "set",
658               [
659                 [
660                   "uuid",
661                   "117f1a07-7ef0-458a-865c-ec7fbb85bc01"
662                 ],
663                 [
664                   "uuid",
665                   "12fd8bdc-e950-4281-aaa9-46e185658f79"
666                 ]
667               ]
668             ]
669           }
670         }
671       }
672     }
673    */
674   const char *path[] = {"Bridge", NULL};
675
676   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
677
678   if (bridges && YAJL_IS_OBJECT(bridges)) {
679     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
680       yajl_val bridge = YAJL_GET_OBJECT(bridges)->values[i];
681       ovs_stats_update_bridge(bridge);
682     }
683   }
684 }
685
686 /* Handle Bridge Table delete event */
687 static void ovs_stats_bridge_table_delete_cb(yajl_val jupdates) {
688   const char *path[] = {"Bridge", NULL};
689   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
690   yajl_val bridge;
691   if (bridges && YAJL_IS_OBJECT(bridges)) {
692     pthread_mutex_lock(&g_stats_lock);
693     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
694       bridge = YAJL_GET_OBJECT(bridges)->values[i];
695       ovs_stats_del_bridge(bridge);
696     }
697     pthread_mutex_unlock(&g_stats_lock);
698   }
699   return;
700 }
701
702 /* Handle JSON with Bridge table initial values */
703 static void ovs_stats_bridge_table_result_cb(yajl_val jresult,
704                                              yajl_val jerror) {
705   if (YAJL_IS_NULL(jerror))
706     ovs_stats_bridge_table_change_cb(jresult);
707   else
708     ERROR("%s: Error received from OvSDB. Table: Bridge", plugin_name);
709   return;
710 }
711
712 /* Update port name and interface UUID(s)*/
713 static int ovs_stats_update_port(const char *uuid, yajl_val port) {
714   const char *new[] = {"new", NULL};
715   const char *name[] = {"name", NULL};
716   yajl_val row;
717   port_list_t *portentry = NULL;
718   if (port && YAJL_IS_OBJECT(port)) {
719     row = yajl_tree_get(port, new, yajl_t_object);
720     if (row && YAJL_IS_OBJECT(row)) {
721       yajl_val port_name = yajl_tree_get(row, name, yajl_t_string);
722       if (port_name && YAJL_IS_STRING(port_name)) {
723         portentry = ovs_stats_get_port(uuid);
724         if (portentry == NULL)
725           portentry = ovs_stats_new_port(NULL, uuid);
726         if (portentry) {
727           pthread_mutex_lock(&g_stats_lock);
728           sstrncpy(portentry->name, YAJL_GET_STRING(port_name),
729                    sizeof(portentry->name));
730           pthread_mutex_unlock(&g_stats_lock);
731
732           yajl_val ifaces_root = ovs_utils_get_value_by_key(row, "interfaces");
733           char *ifaces_root_key =
734               YAJL_GET_STRING(YAJL_GET_ARRAY(ifaces_root)->values[0]);
735
736           char *iface_uuid_str = NULL;
737
738           if (strcmp("set", ifaces_root_key) == 0) {
739             // ifaces_root is ["set", [[ "uuid", "<some_uuid>" ], [ "uuid",
740             // "<another_uuid>" ], ... ]]
741             yajl_val ifaces_list = YAJL_GET_ARRAY(ifaces_root)->values[1];
742
743             // ifaces_list is [[ "uuid", "<some_uuid>" ], [ "uuid",
744             // "<another_uuid>" ], ... ]]
745             for (int i = 0; i < YAJL_GET_ARRAY(ifaces_list)->len; i++) {
746               yajl_val iface_tuple = YAJL_GET_ARRAY(ifaces_list)->values[i];
747
748               // iface_tuple is [ "uuid", "<some_uuid>" ]
749               iface_uuid_str =
750                   YAJL_GET_STRING(YAJL_GET_ARRAY(iface_tuple)->values[1]);
751
752               interface_list_t *iface =
753                   ovs_stats_get_port_interface(portentry, iface_uuid_str);
754
755               if (iface == NULL) {
756                 iface = ovs_stats_new_port_interface(portentry, iface_uuid_str);
757               }
758             }
759           } else {
760             // ifaces_root is [ "uuid", "<some_uuid>" ]
761             iface_uuid_str =
762                 YAJL_GET_STRING(YAJL_GET_ARRAY(ifaces_root)->values[1]);
763
764             interface_list_t *iface =
765                 ovs_stats_get_port_interface(portentry, iface_uuid_str);
766
767             if (iface == NULL) {
768               iface = ovs_stats_new_port_interface(portentry, iface_uuid_str);
769             }
770           }
771         }
772       }
773     }
774   } else {
775     ERROR("Incorrect JSON Port data");
776     return -1;
777   }
778   return 0;
779 }
780
781 /* Delete port from global port list */
782 static int ovs_stats_del_port(const char *uuid) {
783   port_list_t *prev_port = g_port_list_head;
784   for (port_list_t *port = g_port_list_head; port != NULL;
785        prev_port = port, port = port->next) {
786     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0) {
787       if (port == g_port_list_head)
788         g_port_list_head = port->next;
789       else
790         prev_port->next = port->next;
791
792       for (interface_list_t *iface = port->iface; iface != NULL;
793            iface = port->iface) {
794         interface_list_t *del = iface;
795         port->iface = iface->next;
796         sfree(del);
797       }
798
799       sfree(port);
800       break;
801     }
802   }
803   return 0;
804 }
805
806 /* Handle JSON with Port Table change event */
807 static void ovs_stats_port_table_change_cb(yajl_val jupdates) {
808   /* Port Table update example JSON data
809     {
810       "Port": {
811         "ab107d6f-28a1-4257-b1cc-5b742821db8a": {
812           "new": {
813             "name": "br1",
814             "interfaces": [
815               "uuid",
816               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
817             ]
818           }
819         }
820       }
821     }
822    */
823   const char *path[] = {"Port", NULL};
824   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
825   yajl_val port;
826   if (ports && YAJL_IS_OBJECT(ports)) {
827     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
828       port = YAJL_GET_OBJECT(ports)->values[i];
829       ovs_stats_update_port(YAJL_GET_OBJECT(ports)->keys[i], port);
830     }
831   }
832   return;
833 }
834
835 /* Handle JSON with Port table initial values */
836 static void ovs_stats_port_table_result_cb(yajl_val jresult, yajl_val jerror) {
837   if (YAJL_IS_NULL(jerror))
838     ovs_stats_port_table_change_cb(jresult);
839   else
840     ERROR("%s: Error received from OvSDB. Table: Port", plugin_name);
841   return;
842 }
843
844 /* Handle Port Table delete event */
845 static void ovs_stats_port_table_delete_cb(yajl_val jupdates) {
846   const char *path[] = {"Port", NULL};
847   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
848   pthread_mutex_lock(&g_stats_lock);
849   if (ports && YAJL_IS_OBJECT(ports))
850     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
851       ovs_stats_del_port(YAJL_GET_OBJECT(ports)->keys[i]);
852     }
853   pthread_mutex_unlock(&g_stats_lock);
854   return;
855 }
856
857 /* Update interface statistics */
858 static int ovs_stats_update_iface_stats(interface_list_t *iface,
859                                         yajl_val stats) {
860   yajl_val stat;
861   iface_counter counter_index = 0;
862   char *counter_name = NULL;
863   int64_t counter_value = 0;
864   if (stats && YAJL_IS_ARRAY(stats)) {
865     for (size_t i = 0; i < YAJL_GET_ARRAY(stats)->len; i++) {
866       stat = YAJL_GET_ARRAY(stats)->values[i];
867       if (!YAJL_IS_ARRAY(stat))
868         return -1;
869       counter_name = YAJL_GET_STRING(YAJL_GET_ARRAY(stat)->values[0]);
870       counter_index = ovs_stats_counter_name_to_type(counter_name);
871       counter_value = YAJL_GET_INTEGER(YAJL_GET_ARRAY(stat)->values[1]);
872       if (counter_index == not_supported)
873         continue;
874
875       iface->stats[counter_index] = counter_value;
876     }
877   }
878
879   return 0;
880 }
881
882 /* Update interface external_ids */
883 static int ovs_stats_update_iface_ext_ids(interface_list_t *iface,
884                                           yajl_val ext_ids) {
885   yajl_val ext_id;
886   char *key;
887   char *value;
888
889   if (ext_ids && YAJL_IS_ARRAY(ext_ids)) {
890     for (size_t i = 0; i < YAJL_GET_ARRAY(ext_ids)->len; i++) {
891       ext_id = YAJL_GET_ARRAY(ext_ids)->values[i];
892       if (!YAJL_IS_ARRAY(ext_id))
893         return -1;
894       key = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[0]);
895       value = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[1]);
896       if (key && value) {
897         if (strncmp(key, "iface-id", strlen(key)) == 0) {
898           sstrncpy(iface->ex_iface_id, value, sizeof(iface->ex_iface_id));
899         } else if (strncmp(key, "vm-uuid", strlen(key)) == 0) {
900           sstrncpy(iface->ex_vm_id, value, sizeof(iface->ex_vm_id));
901         }
902       }
903     }
904   }
905
906   return 0;
907 }
908
909 /* Get interface statistic and external_ids */
910 static int ovs_stats_update_iface(yajl_val iface_obj) {
911   if (!iface_obj || !YAJL_IS_OBJECT(iface_obj)) {
912     ERROR("ovs_stats plugin: incorrect JSON interface data");
913     return -1;
914   }
915
916   yajl_val row = ovs_utils_get_value_by_key(iface_obj, "new");
917   if (!row || !YAJL_IS_OBJECT(row))
918     return 0;
919
920   yajl_val iface_name = ovs_utils_get_value_by_key(row, "name");
921   if (!iface_name || !YAJL_IS_STRING(iface_name))
922     return 0;
923
924   yajl_val iface_uuid = ovs_utils_get_value_by_key(row, "_uuid");
925   if (!iface_uuid || !YAJL_IS_ARRAY(iface_uuid) ||
926       YAJL_GET_ARRAY(iface_uuid)->len != 2)
927     return 0;
928
929   char *iface_uuid_str = NULL;
930
931   iface_uuid_str = YAJL_GET_STRING(YAJL_GET_ARRAY(iface_uuid)->values[1]);
932
933   if (iface_uuid_str == NULL) {
934     ERROR("ovs_stats plugin: incorrect JSON interface data");
935     return -1;
936   }
937
938   interface_list_t *iface = ovs_stats_get_interface(iface_uuid_str);
939
940   if (iface == NULL)
941     return 0;
942
943   sstrncpy(iface->name, YAJL_GET_STRING(iface_name), sizeof(iface->name));
944
945   yajl_val iface_stats = ovs_utils_get_value_by_key(row, "statistics");
946   yajl_val iface_ext_ids = ovs_utils_get_value_by_key(row, "external_ids");
947
948   /*
949    * {
950         "statistics": [
951           "map",
952           [
953             [
954               "collisions",
955               0
956             ],
957             . . .
958             [
959               "tx_packets",
960               0
961             ]
962           ]
963         ]
964       }
965    Check that statistics is an array with 2 elements
966    */
967
968   if (iface_stats && YAJL_IS_ARRAY(iface_stats) &&
969       YAJL_GET_ARRAY(iface_stats)->len == 2)
970     ovs_stats_update_iface_stats(iface, YAJL_GET_ARRAY(iface_stats)->values[1]);
971   if (iface_ext_ids && YAJL_IS_ARRAY(iface_ext_ids))
972     ovs_stats_update_iface_ext_ids(iface,
973                                    YAJL_GET_ARRAY(iface_ext_ids)->values[1]);
974
975   return 0;
976 }
977
978 /* Delete interface */
979 static int ovs_stats_del_interface(const char *uuid) {
980   port_list_t *port;
981
982   port = ovs_stats_get_port_by_interface_uuid(uuid);
983
984   if (port != NULL) {
985     interface_list_t *prev_iface = NULL;
986
987     for (interface_list_t *iface = port->iface; iface != NULL;
988          iface = port->iface) {
989       if (strncmp(iface->iface_uuid, uuid, strlen(iface->iface_uuid))) {
990
991         interface_list_t *del = iface;
992
993         if (prev_iface == NULL)
994           port->iface = iface->next;
995         else
996           prev_iface->next = iface->next;
997
998         sfree(del);
999         break;
1000       } else
1001         prev_iface = iface;
1002     }
1003   }
1004
1005   return 0;
1006 }
1007
1008 /* Handle JSON with Interface Table change event */
1009 static void ovs_stats_interface_table_change_cb(yajl_val jupdates) {
1010   /* Interface Table update example JSON data
1011     {
1012       "Interface": {
1013         "33a289a0-1d34-4e46-a3c2-3e4066fbecc6": {
1014           "new": {
1015             "name": "br1",
1016             "statistics": [
1017               "map",
1018               [
1019                 [
1020                   "collisions",
1021                   0
1022                 ],
1023                 [
1024                   "rx_bytes",
1025                   0
1026                 ],
1027                . . .
1028                 [
1029                   "tx_packets",
1030                   12617
1031                 ]
1032               ]
1033             ],
1034             "_uuid": [
1035               "uuid",
1036               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
1037             ]
1038             "external_ids": [
1039                 "map",
1040                 [
1041                   [
1042                     "attached-mac",
1043                     "fa:16:3e:7c:1c:4b"
1044                   ],
1045                   [
1046                     "iface-id",
1047                     "a61b7e2b-6951-488a-b4c6-6e91343960b2"
1048                   ],
1049                   [
1050                     "iface-status",
1051                     "active"
1052                   ]
1053                 ]
1054               ]
1055           }
1056         }
1057       }
1058     }
1059    */
1060   const char *path[] = {"Interface", NULL};
1061   yajl_val interfaces = yajl_tree_get(jupdates, path, yajl_t_object);
1062   pthread_mutex_lock(&g_stats_lock);
1063   if (interfaces && YAJL_IS_OBJECT(interfaces))
1064     for (size_t i = 0; i < YAJL_GET_OBJECT(interfaces)->len; i++) {
1065       ovs_stats_update_iface(YAJL_GET_OBJECT(interfaces)->values[i]);
1066     }
1067   pthread_mutex_unlock(&g_stats_lock);
1068   return;
1069 }
1070
1071 /* Handle JSON with Interface table initial values */
1072 static void ovs_stats_interface_table_result_cb(yajl_val jresult,
1073                                                 yajl_val jerror) {
1074   if (YAJL_IS_NULL(jerror))
1075     ovs_stats_interface_table_change_cb(jresult);
1076   else
1077     ERROR("%s: Error received from OvSDB. Table: Interface", plugin_name);
1078   return;
1079 }
1080
1081 /* Handle Interface Table delete event */
1082 static void ovs_stats_interface_table_delete_cb(yajl_val jupdates) {
1083   const char *path[] = {"Interface", NULL};
1084   yajl_val interfaces = yajl_tree_get(jupdates, path, yajl_t_object);
1085   pthread_mutex_lock(&g_stats_lock);
1086   if (interfaces && YAJL_IS_OBJECT(interfaces))
1087     for (size_t i = 0; i < YAJL_GET_OBJECT(interfaces)->len; i++) {
1088       ovs_stats_del_interface(YAJL_GET_OBJECT(interfaces)->keys[i]);
1089     }
1090   pthread_mutex_unlock(&g_stats_lock);
1091   return;
1092 }
1093
1094 /* Setup OVS DB table callbacks  */
1095 static void ovs_stats_initialize(ovs_db_t *pdb) {
1096   const char *bridge_columns[] = {"name", "ports", NULL};
1097   const char *port_columns[] = {"name", "interfaces", NULL};
1098   const char *interface_columns[] = {"name", "statistics", "_uuid",
1099                                      "external_ids", NULL};
1100
1101   /* subscribe to a tables */
1102   ovs_db_table_cb_register(
1103       pdb, "Bridge", bridge_columns, ovs_stats_bridge_table_change_cb,
1104       ovs_stats_bridge_table_result_cb,
1105       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
1106           OVS_DB_TABLE_CB_FLAG_MODIFY);
1107
1108   ovs_db_table_cb_register(pdb, "Bridge", bridge_columns,
1109                            ovs_stats_bridge_table_delete_cb, NULL,
1110                            OVS_DB_TABLE_CB_FLAG_DELETE);
1111
1112   ovs_db_table_cb_register(
1113       pdb, "Port", port_columns, ovs_stats_port_table_change_cb,
1114       ovs_stats_port_table_result_cb,
1115       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
1116           OVS_DB_TABLE_CB_FLAG_MODIFY);
1117
1118   ovs_db_table_cb_register(pdb, "Port", port_columns,
1119                            ovs_stats_port_table_delete_cb, NULL,
1120                            OVS_DB_TABLE_CB_FLAG_DELETE);
1121
1122   ovs_db_table_cb_register(
1123       pdb, "Interface", interface_columns, ovs_stats_interface_table_change_cb,
1124       ovs_stats_interface_table_result_cb,
1125       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
1126           OVS_DB_TABLE_CB_FLAG_MODIFY);
1127
1128   ovs_db_table_cb_register(pdb, "Interface", interface_columns,
1129                            ovs_stats_interface_table_delete_cb, NULL,
1130                            OVS_DB_TABLE_CB_FLAG_DELETE);
1131 }
1132
1133 /* Check if bridge is configured to be monitored in config file */
1134 static int ovs_stats_is_monitored_bridge(const char *br_name) {
1135   /* if no bridges are configured, return true */
1136   if (g_monitored_bridge_list_head == NULL)
1137     return 1;
1138
1139   /* check if given bridge exists */
1140   if (ovs_stats_get_bridge(g_monitored_bridge_list_head, br_name) != NULL)
1141     return 1;
1142
1143   return 0;
1144 }
1145
1146 /* Delete all ports from port list */
1147 static void ovs_stats_free_port_list(port_list_t *head) {
1148   for (port_list_t *i = head; i != NULL;) {
1149     port_list_t *del = i;
1150
1151     for (interface_list_t *iface = i->iface; iface != NULL; iface = i->iface) {
1152       interface_list_t *del2 = iface;
1153       i->iface = iface->next;
1154       sfree(del2);
1155     }
1156
1157     i = i->next;
1158     sfree(del);
1159   }
1160 }
1161
1162 /* Delete all bridges from bridge list */
1163 static void ovs_stats_free_bridge_list(bridge_list_t *head) {
1164   for (bridge_list_t *i = head; i != NULL;) {
1165     bridge_list_t *del = i;
1166     i = i->next;
1167     sfree(del->name);
1168     sfree(del);
1169   }
1170 }
1171
1172 /* Handle OVSDB lost connection callback */
1173 static void ovs_stats_conn_terminate() {
1174   WARNING("Lost connection to OVSDB server");
1175   pthread_mutex_lock(&g_stats_lock);
1176   ovs_stats_free_bridge_list(g_bridge_list_head);
1177   g_bridge_list_head = NULL;
1178   ovs_stats_free_port_list(g_port_list_head);
1179   g_port_list_head = NULL;
1180   pthread_mutex_unlock(&g_stats_lock);
1181 }
1182
1183 /* Parse plugin configuration file and store the config
1184  * in allocated memory. Returns negative value in case of error.
1185  */
1186 static int ovs_stats_plugin_config(oconfig_item_t *ci) {
1187   bridge_list_t *bridge;
1188
1189   for (int i = 0; i < ci->children_num; i++) {
1190     oconfig_item_t *child = ci->children + i;
1191     if (strcasecmp("Address", child->key) == 0) {
1192       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_node,
1193                                     OVS_DB_ADDR_NODE_SIZE) != 0) {
1194         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1195         return -1;
1196       }
1197     } else if (strcasecmp("Port", child->key) == 0) {
1198       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_serv,
1199                                     OVS_DB_ADDR_SERVICE_SIZE) != 0) {
1200         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1201         return -1;
1202       }
1203     } else if (strcasecmp("Socket", child->key) == 0) {
1204       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_unix,
1205                                     OVS_DB_ADDR_UNIX_SIZE) != 0) {
1206         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1207         return -1;
1208       }
1209     } else if (strcasecmp("Bridges", child->key) == 0) {
1210       for (int j = 0; j < child->values_num; j++) {
1211         /* check value type */
1212         if (child->values[j].type != OCONFIG_TYPE_STRING) {
1213           ERROR("%s: Wrong bridge name [idx=%d]. "
1214                 "Bridge name should be string",
1215                 plugin_name, j);
1216           goto cleanup_fail;
1217         }
1218         /* get value */
1219         char const *br_name = child->values[j].value.string;
1220         if ((bridge = ovs_stats_get_bridge(g_monitored_bridge_list_head,
1221                                            br_name)) == NULL) {
1222           if ((bridge = calloc(1, sizeof(bridge_list_t))) == NULL) {
1223             ERROR("%s: Error allocating memory for bridge", plugin_name);
1224             goto cleanup_fail;
1225           } else {
1226             char *br_name_dup = strdup(br_name);
1227             if (br_name_dup == NULL) {
1228               ERROR("%s: strdup() copy bridge name fail", plugin_name);
1229               sfree(bridge);
1230               goto cleanup_fail;
1231             }
1232
1233             pthread_mutex_lock(&g_stats_lock);
1234             /* store bridge name */
1235             bridge->name = br_name_dup;
1236             bridge->next = g_monitored_bridge_list_head;
1237             g_monitored_bridge_list_head = bridge;
1238             pthread_mutex_unlock(&g_stats_lock);
1239             DEBUG("%s: found monitored interface \"%s\"", plugin_name, br_name);
1240           }
1241         }
1242       }
1243     } else if (strcasecmp("InterfaceStats", child->key) == 0) {
1244       if (cf_util_get_boolean(child, &interface_stats) != 0) {
1245         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1246         return -1;
1247       }
1248     } else {
1249       WARNING("%s: option '%s' not allowed here", plugin_name, child->key);
1250       goto cleanup_fail;
1251     }
1252   }
1253   return 0;
1254
1255 cleanup_fail:
1256   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
1257   return -1;
1258 }
1259
1260 /* Initialize OvS Stats plugin*/
1261 static int ovs_stats_plugin_init(void) {
1262   ovs_db_callback_t cb = {.post_conn_init = ovs_stats_initialize,
1263                           .post_conn_terminate = ovs_stats_conn_terminate};
1264
1265   INFO("%s: Connecting to OVS DB using address=%s, service=%s, unix=%s",
1266        plugin_name, ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
1267        ovs_stats_cfg.ovs_db_unix);
1268   /* connect to OvS DB */
1269   if ((g_ovs_db =
1270            ovs_db_init(ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
1271                        ovs_stats_cfg.ovs_db_unix, &cb)) == NULL) {
1272     ERROR("%s: plugin: failed to connect to OvS DB server", plugin_name);
1273     return -1;
1274   }
1275   int err = pthread_mutex_init(&g_stats_lock, NULL);
1276   if (err < 0) {
1277     ERROR("%s: plugin: failed to initialize cache lock", plugin_name);
1278     ovs_db_destroy(g_ovs_db);
1279     return -1;
1280   }
1281   return 0;
1282 }
1283
1284 /* OvS stats read callback. Read bridge/port information and submit it*/
1285 static int ovs_stats_plugin_read(__attribute__((unused)) user_data_t *ud) {
1286   bridge_list_t *bridge;
1287   port_list_t *port;
1288
1289   pthread_mutex_lock(&g_stats_lock);
1290   for (bridge = g_bridge_list_head; bridge != NULL; bridge = bridge->next) {
1291     if (ovs_stats_is_monitored_bridge(bridge->name)) {
1292       for (port = g_port_list_head; port != NULL; port = port->next)
1293         if (port->br == bridge) {
1294           if (strlen(port->name) == 0)
1295             /* Skip port w/o name. This is possible when read callback
1296              * is called after Interface Table update callback but before
1297              * Port table Update callback. Will add this port on next read */
1298             continue;
1299
1300           ovs_stats_submit_port(bridge, port);
1301
1302           if (interface_stats)
1303             ovs_stats_submit_interfaces(bridge, port);
1304         }
1305     } else
1306       continue;
1307   }
1308   pthread_mutex_unlock(&g_stats_lock);
1309   return 0;
1310 }
1311
1312 /* Shutdown OvS Stats plugin */
1313 static int ovs_stats_plugin_shutdown(void) {
1314   DEBUG("OvS Statistics plugin shutting down");
1315   ovs_db_destroy(g_ovs_db);
1316   pthread_mutex_lock(&g_stats_lock);
1317   ovs_stats_free_bridge_list(g_bridge_list_head);
1318   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
1319   ovs_stats_free_port_list(g_port_list_head);
1320   pthread_mutex_unlock(&g_stats_lock);
1321   pthread_mutex_destroy(&g_stats_lock);
1322   return 0;
1323 }
1324
1325 /* Register OvS Stats plugin callbacks */
1326 void module_register(void) {
1327   plugin_register_complex_config(plugin_name, ovs_stats_plugin_config);
1328   plugin_register_init(plugin_name, ovs_stats_plugin_init);
1329   plugin_register_complex_read(NULL, plugin_name, ovs_stats_plugin_read, 0,
1330                                NULL);
1331   plugin_register_shutdown(plugin_name, ovs_stats_plugin_shutdown);
1332 }