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