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