85269afef4065028f5356308905fcb45476a41bd
[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(port_list_t *port) {
236   char devname[PORT_NAME_SIZE_MAX * 2];
237
238   bridge_list_t *bridge = port->br;
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(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   bridge_list_t *bridge = port->br;
352   snprintf(devname, sizeof(devname), "%s.%s", bridge->name, port->name);
353   ovs_stats_submit_one(devname, "if_collisions", NULL,
354                        ovs_stats_get_port_stat_value(port, collisions), meta);
355   ovs_stats_submit_two(devname, "if_dropped", NULL,
356                        ovs_stats_get_port_stat_value(port, rx_dropped),
357                        ovs_stats_get_port_stat_value(port, tx_dropped), meta);
358   ovs_stats_submit_two(devname, "if_errors", NULL,
359                        ovs_stats_get_port_stat_value(port, rx_errors),
360                        ovs_stats_get_port_stat_value(port, tx_errors), meta);
361   ovs_stats_submit_two(devname, "if_packets", NULL,
362                        ovs_stats_get_port_stat_value(port, rx_packets),
363                        ovs_stats_get_port_stat_value(port, tx_packets), meta);
364   ovs_stats_submit_one(devname, "if_rx_errors", "crc",
365                        ovs_stats_get_port_stat_value(port, rx_crc_err), meta);
366   ovs_stats_submit_one(devname, "if_rx_errors", "frame",
367                        ovs_stats_get_port_stat_value(port, rx_frame_err), meta);
368   ovs_stats_submit_one(devname, "if_rx_errors", "over",
369                        ovs_stats_get_port_stat_value(port, rx_over_err), meta);
370   ovs_stats_submit_one(devname, "if_rx_octets", NULL,
371                        ovs_stats_get_port_stat_value(port, rx_bytes), meta);
372   ovs_stats_submit_one(devname, "if_tx_octets", NULL,
373                        ovs_stats_get_port_stat_value(port, tx_bytes), meta);
374   ovs_stats_submit_two(devname, "if_packets", "1_to_64_packets",
375                        ovs_stats_get_port_stat_value(port, rx_1_to_64_packets),
376                        ovs_stats_get_port_stat_value(port, tx_1_to_64_packets),
377                        meta);
378   ovs_stats_submit_two(
379       devname, "if_packets", "65_to_127_packets",
380       ovs_stats_get_port_stat_value(port, rx_65_to_127_packets),
381       ovs_stats_get_port_stat_value(port, tx_65_to_127_packets), meta);
382   ovs_stats_submit_two(
383       devname, "if_packets", "128_to_255_packets",
384       ovs_stats_get_port_stat_value(port, rx_128_to_255_packets),
385       ovs_stats_get_port_stat_value(port, tx_128_to_255_packets), meta);
386   ovs_stats_submit_two(
387       devname, "if_packets", "256_to_511_packets",
388       ovs_stats_get_port_stat_value(port, rx_256_to_511_packets),
389       ovs_stats_get_port_stat_value(port, tx_256_to_511_packets), meta);
390   ovs_stats_submit_two(
391       devname, "if_packets", "512_to_1023_packets",
392       ovs_stats_get_port_stat_value(port, rx_512_to_1023_packets),
393       ovs_stats_get_port_stat_value(port, tx_512_to_1023_packets), meta);
394   ovs_stats_submit_two(
395       devname, "if_packets", "1024_to_1522_packets",
396       ovs_stats_get_port_stat_value(port, rx_1024_to_1522_packets),
397       ovs_stats_get_port_stat_value(port, tx_1024_to_1522_packets), meta);
398   ovs_stats_submit_two(
399       devname, "if_packets", "1523_to_max_packets",
400       ovs_stats_get_port_stat_value(port, rx_1523_to_max_packets),
401       ovs_stats_get_port_stat_value(port, tx_1523_to_max_packets), meta);
402   ovs_stats_submit_two(
403       devname, "if_packets", "broadcast_packets",
404       ovs_stats_get_port_stat_value(port, rx_broadcast_packets),
405       ovs_stats_get_port_stat_value(port, tx_broadcast_packets), meta);
406   ovs_stats_submit_one(
407       devname, "if_multicast", "tx_multicast_packets",
408       ovs_stats_get_port_stat_value(port, tx_multicast_packets), meta);
409   ovs_stats_submit_one(
410       devname, "if_rx_errors", "rx_undersized_errors",
411       ovs_stats_get_port_stat_value(port, rx_undersized_errors), meta);
412   ovs_stats_submit_one(devname, "if_rx_errors", "rx_oversize_errors",
413                        ovs_stats_get_port_stat_value(port, rx_oversize_errors),
414                        meta);
415   ovs_stats_submit_one(
416       devname, "if_rx_errors", "rx_fragmented_errors",
417       ovs_stats_get_port_stat_value(port, rx_fragmented_errors), meta);
418   ovs_stats_submit_one(devname, "if_rx_errors", "rx_jabber_errors",
419                        ovs_stats_get_port_stat_value(port, rx_jabber_errors),
420                        meta);
421
422   meta_data_destroy(meta);
423 }
424
425 static port_list_t *ovs_stats_get_port(const char *uuid) {
426   if (uuid == NULL)
427     return NULL;
428
429   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
430     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0)
431       return port;
432   }
433   return NULL;
434 }
435
436 static port_list_t *ovs_stats_get_port_by_interface_uuid(const char *uuid) {
437   if (uuid == NULL)
438     return NULL;
439
440   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
441     for (interface_list_t *iface = port->iface; iface != NULL;
442          iface = iface->next) {
443       if (strncmp(iface->iface_uuid, uuid, strlen(uuid)) == 0)
444         return port;
445     }
446   }
447   return NULL;
448 }
449
450 static interface_list_t *ovs_stats_get_port_interface(port_list_t *port,
451                                                       const char *uuid) {
452   if (port == NULL || uuid == NULL)
453     return NULL;
454
455   for (interface_list_t *iface = port->iface; iface != NULL;
456        iface = iface->next) {
457     if (strncmp(iface->iface_uuid, uuid, strlen(uuid)) == 0)
458       return iface;
459   }
460   return NULL;
461 }
462
463 static interface_list_t *ovs_stats_get_interface(const char *uuid) {
464   if (uuid == NULL)
465     return NULL;
466
467   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
468     for (interface_list_t *iface = port->iface; iface != NULL;
469          iface = iface->next) {
470       if (strncmp(iface->iface_uuid, uuid, strlen(uuid)) == 0)
471         return iface;
472     }
473   }
474   return NULL;
475 }
476
477 static interface_list_t *ovs_stats_new_port_interface(port_list_t *port,
478                                                       const char *uuid) {
479   if (uuid == NULL)
480     return NULL;
481
482   interface_list_t *iface = ovs_stats_get_port_interface(port, uuid);
483
484   if (iface == NULL) {
485     iface = (interface_list_t *)calloc(1, sizeof(interface_list_t));
486     if (!iface) {
487       ERROR("%s: Error allocating interface", plugin_name);
488       return NULL;
489     }
490     memset(iface->stats, -1, sizeof(int64_t[IFACE_COUNTER_COUNT]));
491     sstrncpy(iface->iface_uuid, uuid, sizeof(iface->iface_uuid));
492     interface_list_t *iface_head = port->iface;
493     iface->next = iface_head;
494     port->iface = iface;
495   }
496   return iface;
497 }
498
499 /* Create or get port by port uuid */
500 static port_list_t *ovs_stats_new_port(bridge_list_t *bridge,
501                                        const char *uuid) {
502   if (uuid == NULL)
503     return NULL;
504
505   port_list_t *port = ovs_stats_get_port(uuid);
506
507   if (port == NULL) {
508     port = (port_list_t *)calloc(1, sizeof(port_list_t));
509     if (!port) {
510       ERROR("%s: Error allocating port", plugin_name);
511       return NULL;
512     }
513     sstrncpy(port->port_uuid, uuid, sizeof(port->port_uuid));
514     port->next = g_port_list_head;
515     g_port_list_head = port;
516   }
517   if (bridge != NULL) {
518     port->br = bridge;
519   }
520   return port;
521 }
522
523 /* Get bridge by name*/
524 static bridge_list_t *ovs_stats_get_bridge(bridge_list_t *head,
525                                            const char *name) {
526   if (name == NULL)
527     return NULL;
528
529   for (bridge_list_t *bridge = head; bridge != NULL; bridge = bridge->next) {
530     if ((strncmp(bridge->name, name, strlen(bridge->name)) == 0) &&
531         strlen(name) == strlen(bridge->name))
532       return bridge;
533   }
534   return NULL;
535 }
536
537 /* Check if bridge is configured to be monitored in config file */
538 static int ovs_stats_is_monitored_bridge(const char *br_name) {
539   /* if no bridges are configured, return true */
540   if (g_monitored_bridge_list_head == NULL)
541     return 1;
542
543   /* check if given bridge exists */
544   if (ovs_stats_get_bridge(g_monitored_bridge_list_head, br_name) != NULL)
545     return 1;
546
547   return 0;
548 }
549
550 /* Delete bridge */
551 static int ovs_stats_del_bridge(yajl_val bridge) {
552   const char *old[] = {"old", NULL};
553   const char *name[] = {"name", NULL};
554
555   if (!bridge || !YAJL_IS_OBJECT(bridge)) {
556     WARNING("%s: Incorrect data for deleting bridge", plugin_name);
557     return 0;
558   }
559
560   yajl_val row = yajl_tree_get(bridge, old, yajl_t_object);
561   if (!row || !YAJL_IS_OBJECT(row))
562     return 0;
563
564   yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
565   if (!br_name || !YAJL_IS_STRING(br_name))
566     return 0;
567
568   bridge_list_t *prev_br = g_bridge_list_head;
569   for (bridge_list_t *br = g_bridge_list_head; br != NULL;
570        prev_br = br, br = br->next) {
571     if ((strncmp(br->name, br_name->u.string, strlen(br->name)) == 0) &&
572         strlen(br->name) == strlen(br_name->u.string)) {
573       if (br == g_bridge_list_head)
574         g_bridge_list_head = br->next;
575       else
576         prev_br->next = br->next;
577       sfree(br->name);
578       sfree(br);
579       break;
580     }
581   }
582   return 0;
583 }
584
585 /* Update Bridge. Create bridge ports*/
586 static int ovs_stats_update_bridge(yajl_val bridge) {
587   const char *new[] = {"new", NULL};
588   const char *name[] = {"name", NULL};
589   const char *ports[] = {"ports", NULL};
590
591   if (!bridge || !YAJL_IS_OBJECT(bridge))
592     goto failure;
593
594   yajl_val row = yajl_tree_get(bridge, new, yajl_t_object);
595   if (!row || !YAJL_IS_OBJECT(row))
596     return 0;
597
598   yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
599   if (!br_name || !YAJL_IS_STRING(br_name))
600     return 0;
601
602   if (!ovs_stats_is_monitored_bridge(YAJL_GET_STRING(br_name)))
603     return 0;
604
605   bridge_list_t *br =
606       ovs_stats_get_bridge(g_bridge_list_head, YAJL_GET_STRING(br_name));
607   if (br == NULL) {
608     br = calloc(1, sizeof(*br));
609     if (!br) {
610       ERROR("%s: calloc(%zu) failed.", plugin_name, sizeof(*br));
611       return -1;
612     }
613
614     char *tmp = YAJL_GET_STRING(br_name);
615     if (tmp != NULL)
616       br->name = strdup(tmp);
617
618     if (br->name == NULL) {
619       sfree(br);
620       ERROR("%s: strdup failed.", plugin_name);
621       return -1;
622     }
623
624     br->next = g_bridge_list_head;
625     g_bridge_list_head = br;
626   }
627
628   yajl_val br_ports = yajl_tree_get(row, ports, yajl_t_array);
629   if (!br_ports || !YAJL_IS_ARRAY(br_ports))
630     return 0;
631
632   char *tmp = YAJL_GET_STRING(br_ports->u.array.values[0]);
633   if (tmp != NULL && strcmp("set", tmp) == 0) {
634     yajl_val *array = YAJL_GET_ARRAY(br_ports)->values;
635     size_t array_len = YAJL_GET_ARRAY(br_ports)->len;
636     if (array != NULL && array_len > 0 && YAJL_IS_ARRAY(array[1])) {
637       if (YAJL_GET_ARRAY(array[1]) == NULL)
638         goto failure;
639
640       yajl_val *ports_arr = YAJL_GET_ARRAY(array[1])->values;
641       size_t ports_num = YAJL_GET_ARRAY(array[1])->len;
642       for (size_t i = 0; i < ports_num && ports_arr != NULL; i++) {
643         tmp = YAJL_GET_STRING(ports_arr[i]->u.array.values[1]);
644         if (tmp != NULL)
645           ovs_stats_new_port(br, tmp);
646         else
647           goto failure;
648       }
649     }
650   } else {
651     ovs_stats_new_port(br, YAJL_GET_STRING(br_ports->u.array.values[1]));
652   }
653
654   return 0;
655
656 failure:
657   ERROR("Incorrect JSON Bridge data");
658   return -1;
659 }
660
661 /* Handle JSON with Bridge Table change event */
662 static void ovs_stats_bridge_table_change_cb(yajl_val jupdates) {
663   /* Bridge Table update example JSON data
664     {
665       "Bridge": {
666         "bb1f8965-5775-46d9-b820-236ca8edbedc": {
667           "new": {
668             "name": "br0",
669             "ports": [
670               "set",
671               [
672                 [
673                   "uuid",
674                   "117f1a07-7ef0-458a-865c-ec7fbb85bc01"
675                 ],
676                 [
677                   "uuid",
678                   "12fd8bdc-e950-4281-aaa9-46e185658f79"
679                 ]
680               ]
681             ]
682           }
683         }
684       }
685     }
686    */
687   const char *path[] = {"Bridge", NULL};
688   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
689
690   if (!bridges || !YAJL_IS_OBJECT(bridges))
691     return;
692
693   pthread_mutex_lock(&g_stats_lock);
694   for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
695     yajl_val bridge = YAJL_GET_OBJECT(bridges)->values[i];
696     ovs_stats_update_bridge(bridge);
697   }
698   pthread_mutex_unlock(&g_stats_lock);
699 }
700
701 /* Handle Bridge Table delete event */
702 static void ovs_stats_bridge_table_delete_cb(yajl_val jupdates) {
703   const char *path[] = {"Bridge", NULL};
704   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
705   if (!bridges || !YAJL_IS_OBJECT(bridges))
706     return;
707
708   pthread_mutex_lock(&g_stats_lock);
709   for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
710     yajl_val bridge = YAJL_GET_OBJECT(bridges)->values[i];
711     ovs_stats_del_bridge(bridge);
712   }
713   pthread_mutex_unlock(&g_stats_lock);
714 }
715
716 /* Handle JSON with Bridge table initial values */
717 static void ovs_stats_bridge_table_result_cb(yajl_val jresult,
718                                              yajl_val jerror) {
719   if (YAJL_IS_NULL(jerror))
720     ovs_stats_bridge_table_change_cb(jresult);
721   else
722     ERROR("%s: Error received from OvSDB. Table: Bridge", plugin_name);
723   return;
724 }
725
726 /* Update port name and interface UUID(s)*/
727 static int ovs_stats_update_port(const char *uuid, yajl_val port) {
728   const char *new[] = {"new", NULL};
729   const char *name[] = {"name", NULL};
730
731   if (!port || !YAJL_IS_OBJECT(port)) {
732     ERROR("Incorrect JSON Port data");
733     return -1;
734   }
735
736   yajl_val row = yajl_tree_get(port, new, yajl_t_object);
737   if (!row || !YAJL_IS_OBJECT(row))
738     return 0;
739
740   yajl_val port_name = yajl_tree_get(row, name, yajl_t_string);
741   if (!port_name || !YAJL_IS_STRING(port_name))
742     return 0;
743
744   /* Create or get port by port uuid */
745   port_list_t *portentry = ovs_stats_new_port(NULL, uuid);
746   if (!portentry)
747     return 0;
748
749   sstrncpy(portentry->name, YAJL_GET_STRING(port_name),
750            sizeof(portentry->name));
751
752   yajl_val ifaces_root = ovs_utils_get_value_by_key(row, "interfaces");
753   char *ifaces_root_key =
754       YAJL_GET_STRING(YAJL_GET_ARRAY(ifaces_root)->values[0]);
755
756   if (strcmp("set", ifaces_root_key) == 0) {
757     // ifaces_root is ["set", [[ "uuid", "<some_uuid>" ], [ "uuid",
758     // "<another_uuid>" ], ... ]]
759     yajl_val ifaces_list = YAJL_GET_ARRAY(ifaces_root)->values[1];
760
761     // ifaces_list is [[ "uuid", "<some_uuid>" ], [ "uuid",
762     // "<another_uuid>" ], ... ]]
763     for (int i = 0; i < YAJL_GET_ARRAY(ifaces_list)->len; i++) {
764       yajl_val iface_tuple = YAJL_GET_ARRAY(ifaces_list)->values[i];
765
766       // iface_tuple is [ "uuid", "<some_uuid>" ]
767       char *iface_uuid_str =
768           YAJL_GET_STRING(YAJL_GET_ARRAY(iface_tuple)->values[1]);
769
770       // Also checks if interface already registered
771       ovs_stats_new_port_interface(portentry, iface_uuid_str);
772     }
773   } else {
774     // ifaces_root is [ "uuid", "<some_uuid>" ]
775     char *iface_uuid_str =
776         YAJL_GET_STRING(YAJL_GET_ARRAY(ifaces_root)->values[1]);
777
778     // Also checks if interface already registered
779     ovs_stats_new_port_interface(portentry, iface_uuid_str);
780   }
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   if (!ports || !YAJL_IS_OBJECT(ports))
830     return;
831
832   pthread_mutex_lock(&g_stats_lock);
833   for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
834     yajl_val port = YAJL_GET_OBJECT(ports)->values[i];
835     ovs_stats_update_port(YAJL_GET_OBJECT(ports)->keys[i], port);
836   }
837   pthread_mutex_unlock(&g_stats_lock);
838   return;
839 }
840
841 /* Handle JSON with Port table initial values */
842 static void ovs_stats_port_table_result_cb(yajl_val jresult, yajl_val jerror) {
843   if (YAJL_IS_NULL(jerror))
844     ovs_stats_port_table_change_cb(jresult);
845   else
846     ERROR("%s: Error received from OvSDB. Table: Port", plugin_name);
847   return;
848 }
849
850 /* Handle Port Table delete event */
851 static void ovs_stats_port_table_delete_cb(yajl_val jupdates) {
852   const char *path[] = {"Port", NULL};
853   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
854   if (!ports || !YAJL_IS_OBJECT(ports))
855     return;
856
857   pthread_mutex_lock(&g_stats_lock);
858   for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
859     ovs_stats_del_port(YAJL_GET_OBJECT(ports)->keys[i]);
860   }
861   pthread_mutex_unlock(&g_stats_lock);
862   return;
863 }
864
865 /* Update interface statistics */
866 static int ovs_stats_update_iface_stats(interface_list_t *iface,
867                                         yajl_val stats) {
868
869   if (!stats || !YAJL_IS_ARRAY(stats))
870     return 0;
871
872   for (size_t i = 0; i < YAJL_GET_ARRAY(stats)->len; i++) {
873     yajl_val stat = YAJL_GET_ARRAY(stats)->values[i];
874     if (!YAJL_IS_ARRAY(stat))
875       return -1;
876
877     char *counter_name = YAJL_GET_STRING(YAJL_GET_ARRAY(stat)->values[0]);
878     iface_counter counter_index = ovs_stats_counter_name_to_type(counter_name);
879     int64_t counter_value = YAJL_GET_INTEGER(YAJL_GET_ARRAY(stat)->values[1]);
880     if (counter_index == not_supported)
881       continue;
882
883     iface->stats[counter_index] = counter_value;
884   }
885
886   return 0;
887 }
888
889 /* Update interface external_ids */
890 static int ovs_stats_update_iface_ext_ids(interface_list_t *iface,
891                                           yajl_val ext_ids) {
892
893   if (!ext_ids || !YAJL_IS_ARRAY(ext_ids))
894     return 0;
895
896   for (size_t i = 0; i < YAJL_GET_ARRAY(ext_ids)->len; i++) {
897     yajl_val ext_id = YAJL_GET_ARRAY(ext_ids)->values[i];
898     if (!YAJL_IS_ARRAY(ext_id))
899       return -1;
900
901     char *key = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[0]);
902     char *value = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[1]);
903     if (key && value) {
904       if (strncmp(key, "iface-id", strlen(key)) == 0) {
905         sstrncpy(iface->ex_iface_id, value, sizeof(iface->ex_iface_id));
906       } else if (strncmp(key, "vm-uuid", strlen(key)) == 0) {
907         sstrncpy(iface->ex_vm_id, value, sizeof(iface->ex_vm_id));
908       }
909     }
910   }
911
912   return 0;
913 }
914
915 /* Get interface statistic and external_ids */
916 static int ovs_stats_update_iface(yajl_val iface_obj) {
917   if (!iface_obj || !YAJL_IS_OBJECT(iface_obj)) {
918     ERROR("ovs_stats plugin: incorrect JSON interface data");
919     return -1;
920   }
921
922   yajl_val row = ovs_utils_get_value_by_key(iface_obj, "new");
923   if (!row || !YAJL_IS_OBJECT(row))
924     return 0;
925
926   yajl_val iface_name = ovs_utils_get_value_by_key(row, "name");
927   if (!iface_name || !YAJL_IS_STRING(iface_name))
928     return 0;
929
930   yajl_val iface_uuid = ovs_utils_get_value_by_key(row, "_uuid");
931   if (!iface_uuid || !YAJL_IS_ARRAY(iface_uuid) ||
932       YAJL_GET_ARRAY(iface_uuid)->len != 2)
933     return 0;
934
935   char *iface_uuid_str = YAJL_GET_STRING(YAJL_GET_ARRAY(iface_uuid)->values[1]);
936   if (iface_uuid_str == NULL) {
937     ERROR("ovs_stats plugin: incorrect JSON interface data");
938     return -1;
939   }
940
941   interface_list_t *iface = ovs_stats_get_interface(iface_uuid_str);
942   if (iface == NULL)
943     return 0;
944
945   sstrncpy(iface->name, YAJL_GET_STRING(iface_name), sizeof(iface->name));
946
947   yajl_val iface_stats = ovs_utils_get_value_by_key(row, "statistics");
948   yajl_val iface_ext_ids = ovs_utils_get_value_by_key(row, "external_ids");
949
950   /*
951    * {
952         "statistics": [
953           "map",
954           [
955             [
956               "collisions",
957               0
958             ],
959             . . .
960             [
961               "tx_packets",
962               0
963             ]
964           ]
965         ]
966       }
967    Check that statistics is an array with 2 elements
968    */
969
970   if (iface_stats && YAJL_IS_ARRAY(iface_stats) &&
971       YAJL_GET_ARRAY(iface_stats)->len == 2)
972     ovs_stats_update_iface_stats(iface, YAJL_GET_ARRAY(iface_stats)->values[1]);
973
974   if (iface_ext_ids && YAJL_IS_ARRAY(iface_ext_ids))
975     ovs_stats_update_iface_ext_ids(iface,
976                                    YAJL_GET_ARRAY(iface_ext_ids)->values[1]);
977
978   return 0;
979 }
980
981 /* Delete interface */
982 static int ovs_stats_del_interface(const char *uuid) {
983   port_list_t *port = ovs_stats_get_port_by_interface_uuid(uuid);
984
985   if (port == NULL)
986     return 0;
987
988   interface_list_t *prev_iface = NULL;
989
990   for (interface_list_t *iface = port->iface; iface != NULL;
991        iface = port->iface) {
992     if (strncmp(iface->iface_uuid, uuid, strlen(iface->iface_uuid))) {
993
994       interface_list_t *del = iface;
995
996       if (prev_iface == NULL)
997         port->iface = iface->next;
998       else
999         prev_iface->next = iface->next;
1000
1001       sfree(del);
1002       break;
1003     } else {
1004       prev_iface = iface;
1005     }
1006   }
1007
1008   return 0;
1009 }
1010
1011 /* Handle JSON with Interface Table change event */
1012 static void ovs_stats_interface_table_change_cb(yajl_val jupdates) {
1013   /* Interface Table update example JSON data
1014     {
1015       "Interface": {
1016         "33a289a0-1d34-4e46-a3c2-3e4066fbecc6": {
1017           "new": {
1018             "name": "br1",
1019             "statistics": [
1020               "map",
1021               [
1022                 [
1023                   "collisions",
1024                   0
1025                 ],
1026                 [
1027                   "rx_bytes",
1028                   0
1029                 ],
1030                . . .
1031                 [
1032                   "tx_packets",
1033                   12617
1034                 ]
1035               ]
1036             ],
1037             "_uuid": [
1038               "uuid",
1039               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
1040             ]
1041             "external_ids": [
1042                 "map",
1043                 [
1044                   [
1045                     "attached-mac",
1046                     "fa:16:3e:7c:1c:4b"
1047                   ],
1048                   [
1049                     "iface-id",
1050                     "a61b7e2b-6951-488a-b4c6-6e91343960b2"
1051                   ],
1052                   [
1053                     "iface-status",
1054                     "active"
1055                   ]
1056                 ]
1057               ]
1058           }
1059         }
1060       }
1061     }
1062    */
1063   const char *path[] = {"Interface", NULL};
1064   yajl_val interfaces = yajl_tree_get(jupdates, path, yajl_t_object);
1065   if (!interfaces || !YAJL_IS_OBJECT(interfaces))
1066     return;
1067
1068   pthread_mutex_lock(&g_stats_lock);
1069   for (size_t i = 0; i < YAJL_GET_OBJECT(interfaces)->len; i++) {
1070     ovs_stats_update_iface(YAJL_GET_OBJECT(interfaces)->values[i]);
1071   }
1072   pthread_mutex_unlock(&g_stats_lock);
1073
1074   return;
1075 }
1076
1077 /* Handle JSON with Interface table initial values */
1078 static void ovs_stats_interface_table_result_cb(yajl_val jresult,
1079                                                 yajl_val jerror) {
1080   if (YAJL_IS_NULL(jerror))
1081     ovs_stats_interface_table_change_cb(jresult);
1082   else
1083     ERROR("%s: Error received from OvSDB. Table: Interface", plugin_name);
1084   return;
1085 }
1086
1087 /* Handle Interface Table delete event */
1088 static void ovs_stats_interface_table_delete_cb(yajl_val jupdates) {
1089   const char *path[] = {"Interface", NULL};
1090   yajl_val interfaces = yajl_tree_get(jupdates, path, yajl_t_object);
1091   if (!interfaces || !YAJL_IS_OBJECT(interfaces))
1092     return;
1093
1094   pthread_mutex_lock(&g_stats_lock);
1095   for (size_t i = 0; i < YAJL_GET_OBJECT(interfaces)->len; i++) {
1096     ovs_stats_del_interface(YAJL_GET_OBJECT(interfaces)->keys[i]);
1097   }
1098   pthread_mutex_unlock(&g_stats_lock);
1099
1100   return;
1101 }
1102
1103 /* Setup OVS DB table callbacks  */
1104 static void ovs_stats_initialize(ovs_db_t *pdb) {
1105   const char *bridge_columns[] = {"name", "ports", NULL};
1106   const char *port_columns[] = {"name", "interfaces", NULL};
1107   const char *interface_columns[] = {"name", "statistics", "_uuid",
1108                                      "external_ids", NULL};
1109
1110   /* subscribe to a tables */
1111   ovs_db_table_cb_register(
1112       pdb, "Bridge", bridge_columns, ovs_stats_bridge_table_change_cb,
1113       ovs_stats_bridge_table_result_cb,
1114       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
1115           OVS_DB_TABLE_CB_FLAG_MODIFY);
1116
1117   ovs_db_table_cb_register(pdb, "Bridge", bridge_columns,
1118                            ovs_stats_bridge_table_delete_cb, NULL,
1119                            OVS_DB_TABLE_CB_FLAG_DELETE);
1120
1121   ovs_db_table_cb_register(
1122       pdb, "Port", port_columns, ovs_stats_port_table_change_cb,
1123       ovs_stats_port_table_result_cb,
1124       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
1125           OVS_DB_TABLE_CB_FLAG_MODIFY);
1126
1127   ovs_db_table_cb_register(pdb, "Port", port_columns,
1128                            ovs_stats_port_table_delete_cb, NULL,
1129                            OVS_DB_TABLE_CB_FLAG_DELETE);
1130
1131   ovs_db_table_cb_register(
1132       pdb, "Interface", interface_columns, ovs_stats_interface_table_change_cb,
1133       ovs_stats_interface_table_result_cb,
1134       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
1135           OVS_DB_TABLE_CB_FLAG_MODIFY);
1136
1137   ovs_db_table_cb_register(pdb, "Interface", interface_columns,
1138                            ovs_stats_interface_table_delete_cb, NULL,
1139                            OVS_DB_TABLE_CB_FLAG_DELETE);
1140 }
1141
1142 /* Delete all ports from port list */
1143 static void ovs_stats_free_port_list(port_list_t *head) {
1144   for (port_list_t *i = head; i != NULL;) {
1145     port_list_t *del = i;
1146
1147     for (interface_list_t *iface = i->iface; iface != NULL; iface = i->iface) {
1148       interface_list_t *del2 = iface;
1149       i->iface = iface->next;
1150       sfree(del2);
1151     }
1152
1153     i = i->next;
1154     sfree(del);
1155   }
1156 }
1157
1158 /* Delete all bridges from bridge list */
1159 static void ovs_stats_free_bridge_list(bridge_list_t *head) {
1160   for (bridge_list_t *i = head; i != NULL;) {
1161     bridge_list_t *del = i;
1162     i = i->next;
1163     sfree(del->name);
1164     sfree(del);
1165   }
1166 }
1167
1168 /* Handle OVSDB lost connection callback */
1169 static void ovs_stats_conn_terminate() {
1170   WARNING("Lost connection to OVSDB server");
1171   pthread_mutex_lock(&g_stats_lock);
1172   ovs_stats_free_bridge_list(g_bridge_list_head);
1173   g_bridge_list_head = NULL;
1174   ovs_stats_free_port_list(g_port_list_head);
1175   g_port_list_head = NULL;
1176   pthread_mutex_unlock(&g_stats_lock);
1177 }
1178
1179 /* Parse plugin configuration file and store the config
1180  * in allocated memory. Returns negative value in case of error.
1181  */
1182 static int ovs_stats_plugin_config(oconfig_item_t *ci) {
1183   bridge_list_t *bridge;
1184
1185   for (int i = 0; i < ci->children_num; i++) {
1186     oconfig_item_t *child = ci->children + i;
1187     if (strcasecmp("Address", child->key) == 0) {
1188       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_node,
1189                                     OVS_DB_ADDR_NODE_SIZE) != 0) {
1190         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1191         return -1;
1192       }
1193     } else if (strcasecmp("Port", child->key) == 0) {
1194       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_serv,
1195                                     OVS_DB_ADDR_SERVICE_SIZE) != 0) {
1196         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1197         return -1;
1198       }
1199     } else if (strcasecmp("Socket", child->key) == 0) {
1200       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_unix,
1201                                     OVS_DB_ADDR_UNIX_SIZE) != 0) {
1202         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1203         return -1;
1204       }
1205     } else if (strcasecmp("Bridges", child->key) == 0) {
1206       for (int j = 0; j < child->values_num; j++) {
1207         /* check value type */
1208         if (child->values[j].type != OCONFIG_TYPE_STRING) {
1209           ERROR("%s: Wrong bridge name [idx=%d]. "
1210                 "Bridge name should be string",
1211                 plugin_name, j);
1212           goto cleanup_fail;
1213         }
1214         /* get value */
1215         char const *br_name = child->values[j].value.string;
1216         if ((bridge = ovs_stats_get_bridge(g_monitored_bridge_list_head,
1217                                            br_name)) == NULL) {
1218           if ((bridge = calloc(1, sizeof(bridge_list_t))) == NULL) {
1219             ERROR("%s: Error allocating memory for bridge", plugin_name);
1220             goto cleanup_fail;
1221           } else {
1222             char *br_name_dup = strdup(br_name);
1223             if (br_name_dup == NULL) {
1224               ERROR("%s: strdup() copy bridge name fail", plugin_name);
1225               sfree(bridge);
1226               goto cleanup_fail;
1227             }
1228
1229             pthread_mutex_lock(&g_stats_lock);
1230             /* store bridge name */
1231             bridge->name = br_name_dup;
1232             bridge->next = g_monitored_bridge_list_head;
1233             g_monitored_bridge_list_head = bridge;
1234             pthread_mutex_unlock(&g_stats_lock);
1235             DEBUG("%s: found monitored interface \"%s\"", plugin_name, br_name);
1236           }
1237         }
1238       }
1239     } else if (strcasecmp("InterfaceStats", child->key) == 0) {
1240       if (cf_util_get_boolean(child, &interface_stats) != 0) {
1241         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
1242         return -1;
1243       }
1244     } else {
1245       WARNING("%s: option '%s' not allowed here", plugin_name, child->key);
1246       goto cleanup_fail;
1247     }
1248   }
1249   return 0;
1250
1251 cleanup_fail:
1252   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
1253   return -1;
1254 }
1255
1256 /* Initialize OvS Stats plugin*/
1257 static int ovs_stats_plugin_init(void) {
1258   ovs_db_callback_t cb = {.post_conn_init = ovs_stats_initialize,
1259                           .post_conn_terminate = ovs_stats_conn_terminate};
1260
1261   INFO("%s: Connecting to OVS DB using address=%s, service=%s, unix=%s",
1262        plugin_name, ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
1263        ovs_stats_cfg.ovs_db_unix);
1264   /* connect to OvS DB */
1265   if ((g_ovs_db =
1266            ovs_db_init(ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
1267                        ovs_stats_cfg.ovs_db_unix, &cb)) == NULL) {
1268     ERROR("%s: plugin: failed to connect to OvS DB server", plugin_name);
1269     return -1;
1270   }
1271   int err = pthread_mutex_init(&g_stats_lock, NULL);
1272   if (err < 0) {
1273     ERROR("%s: plugin: failed to initialize cache lock", plugin_name);
1274     ovs_db_destroy(g_ovs_db);
1275     return -1;
1276   }
1277   return 0;
1278 }
1279
1280 /* OvS stats read callback. Read bridge/port information and submit it*/
1281 static int ovs_stats_plugin_read(__attribute__((unused)) user_data_t *ud) {
1282   pthread_mutex_lock(&g_stats_lock);
1283   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
1284     if (strlen(port->name) == 0)
1285       /* Skip port w/o name. This is possible when read callback
1286        * is called after Interface Table update callback but before
1287        * Port table Update callback. Will add this port on next read */
1288       continue;
1289
1290     /* Skip port if it has no bridge */
1291     if (!port->br)
1292       continue;
1293
1294     ovs_stats_submit_port(port);
1295
1296     if (interface_stats)
1297       ovs_stats_submit_interfaces(port);
1298   }
1299   pthread_mutex_unlock(&g_stats_lock);
1300   return 0;
1301 }
1302
1303 /* Shutdown OvS Stats plugin */
1304 static int ovs_stats_plugin_shutdown(void) {
1305   DEBUG("OvS Statistics plugin shutting down");
1306   ovs_db_destroy(g_ovs_db);
1307   pthread_mutex_lock(&g_stats_lock);
1308   ovs_stats_free_bridge_list(g_bridge_list_head);
1309   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
1310   ovs_stats_free_port_list(g_port_list_head);
1311   pthread_mutex_unlock(&g_stats_lock);
1312   pthread_mutex_destroy(&g_stats_lock);
1313   return 0;
1314 }
1315
1316 /* Register OvS Stats plugin callbacks */
1317 void module_register(void) {
1318   plugin_register_complex_config(plugin_name, ovs_stats_plugin_config);
1319   plugin_register_init(plugin_name, ovs_stats_plugin_init);
1320   plugin_register_complex_read(NULL, plugin_name, ovs_stats_plugin_read, 0,
1321                                NULL);
1322   plugin_register_shutdown(plugin_name, ovs_stats_plugin_shutdown);
1323 }