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