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