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