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