8309223b0243bec4874c486233f5394708965dab
[collectd.git] / src / ovs_stats.c
1 /*
2  * collectd - src/ovs_stats.c
3  *
4  * Copyright(c) 2016 Intel Corporation. All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of
8  * this software and associated documentation files (the "Software"), to deal in
9  * the Software without restriction, including without limitation the rights to
10  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
11  * of the Software, and to permit persons to whom the Software is furnished to
12  * do
13  * so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all
17  * copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  *
27  * Authors:
28  *   Taras Chornyi <tarasx.chornyi@intel.com>
29  */
30
31 #include "common.h"
32
33 #include "utils_ovs.h" /* OvS helpers */
34
35 /* Plugin name */
36 static const char plugin_name[] = "ovs_stats";
37
38 typedef enum iface_counter {
39   not_supported = -1,
40   collisions,
41   rx_bytes,
42   rx_crc_err,
43   rx_dropped,
44   rx_errors,
45   rx_frame_err,
46   rx_over_err,
47   rx_packets,
48   tx_bytes,
49   tx_dropped,
50   tx_errors,
51   tx_packets,
52   rx_1_to_64_packets,
53   rx_65_to_127_packets,
54   rx_128_to_255_packets,
55   rx_256_to_511_packets,
56   rx_512_to_1023_packets,
57   rx_1024_to_1522_packets,
58   rx_1523_to_max_packets,
59   tx_1_to_64_packets,
60   tx_65_to_127_packets,
61   tx_128_to_255_packets,
62   tx_256_to_511_packets,
63   tx_512_to_1023_packets,
64   tx_1024_to_1522_packets,
65   tx_1523_to_max_packets,
66   tx_multicast_packets,
67   rx_broadcast_packets,
68   tx_broadcast_packets,
69   rx_undersized_errors,
70   rx_oversize_errors,
71   rx_fragmented_errors,
72   rx_jabber_errors,
73   __iface_counter_max
74 } iface_counter;
75
76 #define IFACE_COUNTER_MAX (__iface_counter_max - 1)
77 #define IFACE_COUNTER_COUNT (__iface_counter_max)
78 #define PORT_NAME_SIZE_MAX 255
79 #define UUID_SIZE 64
80
81 typedef struct port_s {
82   char name[PORT_NAME_SIZE_MAX];      /* Port name */
83   char port_uuid[UUID_SIZE];          /* Port table _uuid */
84   char iface_uuid[UUID_SIZE];         /* Interface table uuid */
85   char ex_iface_id[UUID_SIZE];        /* External iface id */
86   char ex_vm_id[UUID_SIZE];           /* External vm id */
87   int64_t stats[IFACE_COUNTER_COUNT]; /* Port statistics */
88   struct bridge_list_s *br;           /* Pointer to bridge */
89   struct port_s *next;                /* Next port */
90 } port_list_t;
91
92 typedef struct bridge_list_s {
93   char *name;                 /* Bridge name */
94   struct bridge_list_s *next; /* Next bridge*/
95 } bridge_list_t;
96
97 static const char *const iface_counter_table[IFACE_COUNTER_COUNT] = {
98         [collisions] = "collisions",
99         [rx_bytes] = "rx_bytes",
100         [rx_crc_err] = "rx_crc_err",
101         [rx_dropped] = "rx_dropped",
102         [rx_errors] = "rx_errors",
103         [rx_frame_err] = "rx_frame_err",
104         [rx_over_err] = "rx_over_err",
105         [rx_packets] = "rx_packets",
106         [tx_bytes] = "tx_bytes",
107         [tx_dropped] = "tx_dropped",
108         [tx_errors] = "tx_errors",
109         [tx_packets] = "tx_packets",
110         [rx_1_to_64_packets] = "rx_1_to_64_packets",
111         [rx_65_to_127_packets] = "rx_65_to_127_packets",
112         [rx_128_to_255_packets] = "rx_128_to_255_packets",
113         [rx_256_to_511_packets] = "rx_256_to_511_packets",
114         [rx_512_to_1023_packets] = "rx_512_to_1023_packets",
115         [rx_1024_to_1522_packets] = "rx_1024_to_1518_packets",
116         [rx_1523_to_max_packets] = "rx_1523_to_max_packets",
117         [tx_1_to_64_packets] = "tx_1_to_64_packets",
118         [tx_65_to_127_packets] = "tx_65_to_127_packets",
119         [tx_128_to_255_packets] = "tx_128_to_255_packets",
120         [tx_256_to_511_packets] = "tx_256_to_511_packets",
121         [tx_512_to_1023_packets] = "tx_512_to_1023_packets",
122         [tx_1024_to_1522_packets] = "tx_1024_to_1518_packets",
123         [tx_1523_to_max_packets] = "tx_1523_to_max_packets",
124         [tx_multicast_packets] = "tx_multicast_packets",
125         [rx_broadcast_packets] = "rx_broadcast_packets",
126         [tx_broadcast_packets] = "tx_broadcast_packets",
127         [rx_undersized_errors] = "rx_undersized_errors",
128         [rx_oversize_errors] = "rx_oversize_errors",
129         [rx_fragmented_errors] = "rx_fragmented_errors",
130         [rx_jabber_errors] = "rx_jabber_errors",
131 };
132
133 /* Entry into the list of network bridges */
134 static bridge_list_t *g_bridge_list_head;
135
136 /* Entry into the list of monitored network bridges */
137 static bridge_list_t *g_monitored_bridge_list_head;
138
139 /* entry into the list of network bridges */
140 static port_list_t *g_port_list_head;
141
142 /* lock for statistics cache */
143 static pthread_mutex_t g_stats_lock;
144
145 /* OvS DB socket */
146 static ovs_db_t *g_ovs_db;
147
148 /* OVS stats configuration data */
149 struct ovs_stats_config_s {
150   char ovs_db_node[OVS_DB_ADDR_NODE_SIZE];    /* OVS DB node */
151   char ovs_db_serv[OVS_DB_ADDR_SERVICE_SIZE]; /* OVS DB service */
152   char ovs_db_unix[OVS_DB_ADDR_UNIX_SIZE];    /* OVS DB unix socket path */
153 };
154 typedef struct ovs_stats_config_s ovs_stats_config_t;
155
156 static ovs_stats_config_t ovs_stats_cfg = {
157     .ovs_db_node = "localhost", /* use default OVS DB node */
158     .ovs_db_serv = "6640",      /* use default OVS DB service */
159 };
160
161 static iface_counter ovs_stats_counter_name_to_type(const char *counter) {
162   iface_counter index = not_supported;
163
164   if (counter == NULL)
165     return not_supported;
166
167   for (int i = 0; i < IFACE_COUNTER_COUNT; i++) {
168     if (strncmp(iface_counter_table[i], counter,
169                 strlen(iface_counter_table[i])) == 0) {
170       index = i;
171       break;
172     }
173   }
174   return index;
175 }
176
177 static void ovs_stats_submit_one(const char *dev, const char *type,
178                                  const char *type_instance, derive_t value,
179                                  meta_data_t *meta) {
180   /* if counter is less than 0 - skip it*/
181   if (value < 0)
182     return;
183   value_list_t vl = VALUE_LIST_INIT;
184
185   vl.values = &(value_t){.derive = value};
186   vl.values_len = 1;
187   vl.meta = meta;
188
189   sstrncpy(vl.plugin, plugin_name, sizeof(vl.plugin));
190   sstrncpy(vl.plugin_instance, dev, sizeof(vl.plugin_instance));
191   sstrncpy(vl.type, type, sizeof(vl.type));
192
193   if (type_instance != NULL)
194     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
195
196   plugin_dispatch_values(&vl);
197 }
198
199 static void ovs_stats_submit_two(const char *dev, const char *type,
200                                  const char *type_instance, derive_t rx,
201                                  derive_t tx, meta_data_t *meta) {
202   /* if counter is less than 0 - skip it*/
203   if (rx < 0 || tx < 0)
204     return;
205   value_list_t vl = VALUE_LIST_INIT;
206   value_t values[] = {{.derive = rx}, {.derive = tx}};
207
208   vl.values = values;
209   vl.values_len = STATIC_ARRAY_SIZE(values);
210   vl.meta = meta;
211
212   sstrncpy(vl.plugin, plugin_name, sizeof(vl.plugin));
213   sstrncpy(vl.plugin_instance, dev, sizeof(vl.plugin_instance));
214   sstrncpy(vl.type, type, sizeof(vl.type));
215
216   if (type_instance != NULL)
217     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
218
219   plugin_dispatch_values(&vl);
220 }
221
222 static port_list_t *ovs_stats_get_port(const char *uuid) {
223   if (uuid == NULL)
224     return NULL;
225
226   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next) {
227     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0)
228       return port;
229   }
230   return NULL;
231 }
232
233 static port_list_t *ovs_stats_get_port_by_name(const char *name) {
234   if (name == NULL)
235     return NULL;
236
237   for (port_list_t *port = g_port_list_head; port != NULL; port = port->next)
238     if ((strncmp(port->name, name, strlen(port->name)) == 0) &&
239         strlen(name) == strlen(port->name))
240       return port;
241   return NULL;
242 }
243
244 /* Create or get port by port uuid */
245 static port_list_t *ovs_stats_new_port(bridge_list_t *bridge,
246                                        const char *uuid) {
247   port_list_t *port = ovs_stats_get_port(uuid);
248
249   if (port == NULL) {
250     port = (port_list_t *)calloc(1, sizeof(port_list_t));
251     if (!port) {
252       ERROR("%s: Error allocating port", plugin_name);
253       return NULL;
254     }
255     memset(port->stats, -1, sizeof(int64_t[IFACE_COUNTER_COUNT]));
256     sstrncpy(port->port_uuid, uuid, sizeof(port->port_uuid));
257     pthread_mutex_lock(&g_stats_lock);
258     port->next = g_port_list_head;
259     g_port_list_head = port;
260     pthread_mutex_unlock(&g_stats_lock);
261   }
262   if (bridge != NULL) {
263     pthread_mutex_lock(&g_stats_lock);
264     port->br = bridge;
265     pthread_mutex_unlock(&g_stats_lock);
266   }
267   return port;
268 }
269
270 /* Get bridge by name*/
271 static bridge_list_t *ovs_stats_get_bridge(bridge_list_t *head,
272                                            const char *name) {
273   if (name == NULL)
274     return NULL;
275
276   for (bridge_list_t *bridge = head; bridge != NULL; bridge = bridge->next) {
277     if ((strncmp(bridge->name, name, strlen(bridge->name)) == 0) &&
278         strlen(name) == strlen(bridge->name))
279       return bridge;
280   }
281   return NULL;
282 }
283
284 /* Delete bridge */
285 static int ovs_stats_del_bridge(yajl_val bridge) {
286   const char *old[] = {"old", NULL};
287   const char *name[] = {"name", NULL};
288
289   yajl_val row;
290
291   if (bridge && YAJL_IS_OBJECT(bridge)) {
292     row = yajl_tree_get(bridge, old, yajl_t_object);
293     if (row && YAJL_IS_OBJECT(row)) {
294       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
295       if (br_name && YAJL_IS_STRING(br_name)) {
296         bridge_list_t *prev_br = g_bridge_list_head;
297         for (bridge_list_t *br = g_bridge_list_head; br != NULL;
298              prev_br = br, br = br->next) {
299           if ((strncmp(br->name, br_name->u.string, strlen(br->name)) == 0) &&
300               strlen(br->name) == strlen(br_name->u.string)) {
301             if (br == g_bridge_list_head)
302               g_bridge_list_head = br->next;
303             else
304               prev_br->next = br->next;
305             sfree(br->name);
306             sfree(br);
307             break;
308           }
309         }
310       }
311     }
312   } else
313     WARNING("%s: Incorrect data for deleting bridge", plugin_name);
314   return 0;
315 }
316
317 /* Update Bridge. Create bridge ports*/
318 static int ovs_stats_update_bridge(yajl_val bridge) {
319   const char *new[] = {"new", NULL};
320   const char *name[] = {"name", NULL};
321   const char *ports[] = {"ports", NULL};
322   bridge_list_t *br = NULL;
323
324   if (bridge && YAJL_IS_OBJECT(bridge)) {
325     yajl_val row = yajl_tree_get(bridge, new, yajl_t_object);
326     if (row && YAJL_IS_OBJECT(row)) {
327       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
328       yajl_val br_ports = yajl_tree_get(row, ports, yajl_t_array);
329       if (br_name && YAJL_IS_STRING(br_name)) {
330         br = ovs_stats_get_bridge(g_bridge_list_head, YAJL_GET_STRING(br_name));
331         pthread_mutex_lock(&g_stats_lock);
332         if (br == NULL) {
333           br = (bridge_list_t *)calloc(1, sizeof(bridge_list_t));
334           if (!br) {
335             pthread_mutex_unlock(&g_stats_lock);
336             ERROR("%s: Error allocating memory for bridge", plugin_name);
337             return -1;
338           }
339           char *tmp = YAJL_GET_STRING(br_name);
340
341           if (tmp != NULL)
342             br->name = strdup(tmp);
343           if (br->name == NULL) {
344             sfree(br);
345             pthread_mutex_unlock(&g_stats_lock);
346             return -1;
347           }
348           br->next = g_bridge_list_head;
349           g_bridge_list_head = br;
350         }
351         pthread_mutex_unlock(&g_stats_lock);
352       }
353       if (br_ports && YAJL_IS_ARRAY(br_ports)) {
354         char *tmp = YAJL_GET_STRING(br_ports->u.array.values[0]);
355         if (tmp != NULL && strcmp("set", tmp) == 0) {
356           yajl_val *array = YAJL_GET_ARRAY(br_ports)->values;
357           size_t array_len = YAJL_GET_ARRAY(br_ports)->len;
358           if (array != NULL && array_len > 0 && YAJL_IS_ARRAY(array[1])) {
359             yajl_val *ports_arr = YAJL_GET_ARRAY(array[1])->values;
360             size_t ports_num = YAJL_GET_ARRAY(array[1])->len;
361             for (size_t i = 0; i < ports_num && ports_arr != NULL; i++)
362               ovs_stats_new_port(
363                   br, YAJL_GET_STRING(ports_arr[i]->u.array.values[1]));
364           }
365         } else
366           ovs_stats_new_port(br, YAJL_GET_STRING(br_ports->u.array.values[1]));
367       }
368     }
369   } else {
370     ERROR("Incorrect JSON Bridge data");
371     return -1;
372   }
373   return 0;
374 }
375
376 /* Handle JSON with Bridge Table change event */
377 static void ovs_stats_bridge_table_change_cb(yajl_val jupdates) {
378   /* Bridge Table update example JSON data
379     {
380       "Bridge": {
381         "bb1f8965-5775-46d9-b820-236ca8edbedc": {
382           "new": {
383             "name": "br0",
384             "ports": [
385               "set",
386               [
387                 [
388                   "uuid",
389                   "117f1a07-7ef0-458a-865c-ec7fbb85bc01"
390                 ],
391                 [
392                   "uuid",
393                   "12fd8bdc-e950-4281-aaa9-46e185658f79"
394                 ]
395               ]
396             ]
397           }
398         }
399       }
400     }
401    */
402   const char *path[] = {"Bridge", NULL};
403
404   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
405
406   if (bridges && YAJL_IS_OBJECT(bridges)) {
407     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
408       yajl_val bridge = YAJL_GET_OBJECT(bridges)->values[i];
409       ovs_stats_update_bridge(bridge);
410     }
411   }
412 }
413
414 /* Handle Bridge Table delete event */
415 static void ovs_stats_bridge_table_delete_cb(yajl_val jupdates) {
416   const char *path[] = {"Bridge", NULL};
417   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
418   yajl_val bridge;
419   if (bridges && YAJL_IS_OBJECT(bridges)) {
420     pthread_mutex_lock(&g_stats_lock);
421     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
422       bridge = YAJL_GET_OBJECT(bridges)->values[i];
423       ovs_stats_del_bridge(bridge);
424     }
425     pthread_mutex_unlock(&g_stats_lock);
426   }
427   return;
428 }
429
430 /* Handle JSON with Bridge table initial values */
431 static void ovs_stats_bridge_table_result_cb(yajl_val jresult,
432                                              yajl_val jerror) {
433   if (YAJL_IS_NULL(jerror))
434     ovs_stats_bridge_table_change_cb(jresult);
435   else
436     ERROR("%s: Error received from OvSDB. Table: Bridge", plugin_name);
437   return;
438 }
439
440 /* Update port name */
441 static int ovs_stats_update_port(const char *uuid, yajl_val port) {
442   const char *new[] = {"new", NULL};
443   const char *name[] = {"name", NULL};
444   yajl_val row;
445   port_list_t *portentry = NULL;
446   if (port && YAJL_IS_OBJECT(port)) {
447     row = yajl_tree_get(port, new, yajl_t_object);
448     if (row && YAJL_IS_OBJECT(row)) {
449       yajl_val port_name = yajl_tree_get(row, name, yajl_t_string);
450       if (port_name && YAJL_IS_STRING(port_name)) {
451         portentry = ovs_stats_get_port(uuid);
452         if (portentry == NULL)
453           portentry = ovs_stats_new_port(NULL, uuid);
454         if (portentry) {
455           pthread_mutex_lock(&g_stats_lock);
456           sstrncpy(portentry->name, YAJL_GET_STRING(port_name),
457                    sizeof(portentry->name));
458           pthread_mutex_unlock(&g_stats_lock);
459         }
460       }
461     }
462   } else {
463     ERROR("Incorrect JSON Port data");
464     return -1;
465   }
466   return 0;
467 }
468
469 /* Delete port from global port list */
470 static int ovs_stats_del_port(const char *uuid) {
471   port_list_t *prev_port = g_port_list_head;
472   for (port_list_t *port = g_port_list_head; port != NULL;
473        prev_port = port, port = port->next) {
474     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0) {
475       if (port == g_port_list_head)
476         g_port_list_head = port->next;
477       else
478         prev_port->next = port->next;
479       sfree(port);
480       break;
481     }
482   }
483   return 0;
484 }
485
486 /* Handle JSON with Port Table change event */
487 static void ovs_stats_port_table_change_cb(yajl_val jupdates) {
488   /* Port Table update example JSON data
489     {
490       "Port": {
491         "ab107d6f-28a1-4257-b1cc-5b742821db8a": {
492           "new": {
493             "name": "br1",
494             "interfaces": [
495               "uuid",
496               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
497             ]
498           }
499         }
500       }
501     }
502    */
503   const char *path[] = {"Port", NULL};
504   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
505   yajl_val port;
506   if (ports && YAJL_IS_OBJECT(ports)) {
507     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
508       port = YAJL_GET_OBJECT(ports)->values[i];
509       ovs_stats_update_port(YAJL_GET_OBJECT(ports)->keys[i], port);
510     }
511   }
512   return;
513 }
514
515 /* Handle JSON with Port table initial values */
516 static void ovs_stats_port_table_result_cb(yajl_val jresult, yajl_val jerror) {
517   if (YAJL_IS_NULL(jerror))
518     ovs_stats_port_table_change_cb(jresult);
519   else
520     ERROR("%s: Error received from OvSDB. Table: Port", plugin_name);
521   return;
522 }
523
524 /* Handle Port Table delete event */
525 static void ovs_stats_port_table_delete_cb(yajl_val jupdates) {
526   const char *path[] = {"Port", NULL};
527   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
528   pthread_mutex_lock(&g_stats_lock);
529   if (ports && YAJL_IS_OBJECT(ports))
530     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
531       ovs_stats_del_port(YAJL_GET_OBJECT(ports)->keys[i]);
532     }
533   pthread_mutex_unlock(&g_stats_lock);
534   return;
535 }
536
537 /* Update interface statistics */
538 static int ovs_stats_update_iface_stats(port_list_t *port, yajl_val stats) {
539   yajl_val stat;
540   iface_counter counter_index = 0;
541   char *counter_name = NULL;
542   int64_t counter_value = 0;
543   if (stats && YAJL_IS_ARRAY(stats))
544     for (size_t i = 0; i < YAJL_GET_ARRAY(stats)->len; i++) {
545       stat = YAJL_GET_ARRAY(stats)->values[i];
546       if (!YAJL_IS_ARRAY(stat))
547         return -1;
548       counter_name = YAJL_GET_STRING(YAJL_GET_ARRAY(stat)->values[0]);
549       counter_index = ovs_stats_counter_name_to_type(counter_name);
550       counter_value = YAJL_GET_INTEGER(YAJL_GET_ARRAY(stat)->values[1]);
551       if (counter_index == not_supported)
552         continue;
553       port->stats[counter_index] = counter_value;
554     }
555
556   return 0;
557 }
558
559 /* Update interface external_ids */
560 static int ovs_stats_update_iface_ext_ids(port_list_t *port, yajl_val ext_ids) {
561   yajl_val ext_id;
562   char *key;
563   char *value;
564
565   if (ext_ids && YAJL_IS_ARRAY(ext_ids))
566     for (size_t i = 0; i < YAJL_GET_ARRAY(ext_ids)->len; i++) {
567       ext_id = YAJL_GET_ARRAY(ext_ids)->values[i];
568       if (!YAJL_IS_ARRAY(ext_id))
569         return -1;
570       key = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[0]);
571       value = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[1]);
572       if (key && value) {
573         if (strncmp(key, "iface-id", strlen(key)) == 0)
574           sstrncpy(port->ex_iface_id, value, sizeof(port->ex_iface_id));
575         else if (strncmp(key, "vm-uuid", strlen(key)) == 0)
576           sstrncpy(port->ex_vm_id, value, sizeof(port->ex_vm_id));
577       }
578     }
579
580   return 0;
581 }
582
583 /* Get interface statistic and external_ids */
584 static int ovs_stats_update_iface(yajl_val iface) {
585   yajl_val row;
586   port_list_t *port = NULL;
587   if (iface && YAJL_IS_OBJECT(iface)) {
588     row = ovs_utils_get_value_by_key(iface, "new");
589     if (row && YAJL_IS_OBJECT(row)) {
590       yajl_val iface_name = ovs_utils_get_value_by_key(row, "name");
591       yajl_val iface_stats = ovs_utils_get_value_by_key(row, "statistics");
592       yajl_val iface_ext_ids = ovs_utils_get_value_by_key(row, "external_ids");
593       yajl_val iface_uuid = ovs_utils_get_value_by_key(row, "_uuid");
594       if (iface_name && YAJL_IS_STRING(iface_name)) {
595         port = ovs_stats_get_port_by_name(YAJL_GET_STRING(iface_name));
596         if (port == NULL)
597           return 0;
598       }
599       /*
600        * {
601             "statistics": [
602               "map",
603               [
604                 [
605                   "collisions",
606                   0
607                 ],
608                 . . .
609                 [
610                   "tx_packets",
611                   0
612                 ]
613               ]
614             ]
615           }
616        Check that statistics is an array with 2 elements
617        */
618       if (iface_stats && YAJL_IS_ARRAY(iface_stats) &&
619           YAJL_GET_ARRAY(iface_stats)->len == 2)
620         ovs_stats_update_iface_stats(port,
621                                      YAJL_GET_ARRAY(iface_stats)->values[1]);
622       if (iface_ext_ids && YAJL_IS_ARRAY(iface_ext_ids))
623         ovs_stats_update_iface_ext_ids(
624             port, YAJL_GET_ARRAY(iface_ext_ids)->values[1]);
625       if (iface_uuid && YAJL_IS_ARRAY(iface_uuid) &&
626           YAJL_GET_ARRAY(iface_uuid)->len == 2)
627         sstrncpy(port->iface_uuid,
628                  YAJL_GET_STRING(YAJL_GET_ARRAY(iface_uuid)->values[1]),
629                  sizeof(port->iface_uuid));
630     }
631   } else {
632     ERROR("Incorrect JSON Port data");
633     return -1;
634   }
635   return 0;
636 }
637
638 /* Handle JSON with Interface Table change event */
639 static void ovs_stats_interface_table_change_cb(yajl_val jupdates) {
640   /* Interface Table update example JSON data
641     {
642       "Interface": {
643         "33a289a0-1d34-4e46-a3c2-3e4066fbecc6": {
644           "new": {
645             "name": "br1",
646             "statistics": [
647               "map",
648               [
649                 [
650                   "collisions",
651                   0
652                 ],
653                 [
654                   "rx_bytes",
655                   0
656                 ],
657                . . .
658                 [
659                   "tx_packets",
660                   12617
661                 ]
662               ]
663             ],
664             "_uuid": [
665               "uuid",
666               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
667             ]
668             "external_ids": [
669                 "map",
670                 [
671                   [
672                     "attached-mac",
673                     "fa:16:3e:7c:1c:4b"
674                   ],
675                   [
676                     "iface-id",
677                     "a61b7e2b-6951-488a-b4c6-6e91343960b2"
678                   ],
679                   [
680                     "iface-status",
681                     "active"
682                   ]
683                 ]
684               ]
685           }
686         }
687       }
688     }
689    */
690   const char *path[] = {"Interface", NULL};
691   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
692   pthread_mutex_lock(&g_stats_lock);
693   if (ports && YAJL_IS_OBJECT(ports))
694     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++)
695       ovs_stats_update_iface(YAJL_GET_OBJECT(ports)->values[i]);
696   pthread_mutex_unlock(&g_stats_lock);
697   return;
698 }
699
700 /* Handle JSON with Interface table initial values */
701 static void ovs_stats_interface_table_result_cb(yajl_val jresult,
702                                                 yajl_val jerror) {
703   if (YAJL_IS_NULL(jerror))
704     ovs_stats_interface_table_change_cb(jresult);
705   else
706     ERROR("%s: Error received from OvSDB. Table: Interface", plugin_name);
707   return;
708 }
709
710 /* Setup OVS DB table callbacks  */
711 static void ovs_stats_initialize(ovs_db_t *pdb) {
712   const char *bridge_columns[] = {"name", "ports", NULL};
713   const char *port_columns[] = {"name", "interfaces", NULL};
714   const char *interface_columns[] = {"name", "statistics", "_uuid",
715                                      "external_ids", NULL};
716
717   /* subscribe to a tables */
718   ovs_db_table_cb_register(
719       pdb, "Bridge", bridge_columns, ovs_stats_bridge_table_change_cb,
720       ovs_stats_bridge_table_result_cb,
721       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
722           OVS_DB_TABLE_CB_FLAG_MODIFY);
723
724   ovs_db_table_cb_register(pdb, "Bridge", bridge_columns,
725                            ovs_stats_bridge_table_delete_cb, NULL,
726                            OVS_DB_TABLE_CB_FLAG_DELETE);
727
728   ovs_db_table_cb_register(
729       pdb, "Port", port_columns, ovs_stats_port_table_change_cb,
730       ovs_stats_port_table_result_cb,
731       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
732           OVS_DB_TABLE_CB_FLAG_MODIFY);
733
734   ovs_db_table_cb_register(pdb, "Port", port_columns,
735                            ovs_stats_port_table_delete_cb, NULL,
736                            OVS_DB_TABLE_CB_FLAG_DELETE);
737
738   ovs_db_table_cb_register(
739       pdb, "Interface", interface_columns, ovs_stats_interface_table_change_cb,
740       ovs_stats_interface_table_result_cb,
741       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
742           OVS_DB_TABLE_CB_FLAG_MODIFY);
743 }
744
745 /* Check if bridge is configured to be monitored in config file */
746 static int ovs_stats_is_monitored_bridge(const char *br_name) {
747   /* if no bridges are configured, return true */
748   if (g_monitored_bridge_list_head == NULL)
749     return 1;
750
751   /* check if given bridge exists */
752   if (ovs_stats_get_bridge(g_monitored_bridge_list_head, br_name) != NULL)
753     return 1;
754
755   return 0;
756 }
757
758 /* Delete all ports from port list */
759 static void ovs_stats_free_port_list(port_list_t *head) {
760   for (port_list_t *i = head; i != NULL;) {
761     port_list_t *del = i;
762     i = i->next;
763     sfree(del);
764   }
765 }
766
767 /* Delete all bridges from bridge list */
768 static void ovs_stats_free_bridge_list(bridge_list_t *head) {
769   for (bridge_list_t *i = head; i != NULL;) {
770     bridge_list_t *del = i;
771     i = i->next;
772     sfree(del->name);
773     sfree(del);
774   }
775 }
776
777 /* Handle OVSDB lost connection callback */
778 static void ovs_stats_conn_terminate() {
779   WARNING("Lost connection to OVSDB server");
780   pthread_mutex_lock(&g_stats_lock);
781   ovs_stats_free_bridge_list(g_bridge_list_head);
782   g_bridge_list_head = NULL;
783   ovs_stats_free_port_list(g_port_list_head);
784   g_port_list_head = NULL;
785   pthread_mutex_unlock(&g_stats_lock);
786 }
787
788 /* Parse plugin configuration file and store the config
789  * in allocated memory. Returns negative value in case of error.
790  */
791 static int ovs_stats_plugin_config(oconfig_item_t *ci) {
792   bridge_list_t *bridge;
793
794   for (int i = 0; i < ci->children_num; i++) {
795     oconfig_item_t *child = ci->children + i;
796     if (strcasecmp("Address", child->key) == 0) {
797       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_node,
798                                     OVS_DB_ADDR_NODE_SIZE) != 0) {
799         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
800         return -1;
801       }
802     } else if (strcasecmp("Port", child->key) == 0) {
803       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_serv,
804                                     OVS_DB_ADDR_SERVICE_SIZE) != 0) {
805         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
806         return -1;
807       }
808     } else if (strcasecmp("Socket", child->key) == 0) {
809       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_unix,
810                                     OVS_DB_ADDR_UNIX_SIZE) != 0) {
811         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
812         return -1;
813       }
814     } else if (strcasecmp("Bridges", child->key) == 0) {
815       for (int j = 0; j < child->values_num; j++) {
816         /* check value type */
817         if (child->values[j].type != OCONFIG_TYPE_STRING) {
818           ERROR("%s: Wrong bridge name [idx=%d]. "
819                 "Bridge name should be string",
820                 plugin_name, j);
821           goto cleanup_fail;
822         }
823         /* get value */
824         char const *br_name = child->values[j].value.string;
825         if ((bridge = ovs_stats_get_bridge(g_monitored_bridge_list_head,
826                                            br_name)) == NULL) {
827           if ((bridge = calloc(1, sizeof(bridge_list_t))) == NULL) {
828             ERROR("%s: Error allocating memory for bridge", plugin_name);
829             goto cleanup_fail;
830           } else {
831             char *br_name_dup = strdup(br_name);
832             if (br_name_dup == NULL) {
833               ERROR("%s: strdup() copy bridge name fail", plugin_name);
834               goto cleanup_fail;
835             }
836
837             pthread_mutex_lock(&g_stats_lock);
838             /* store bridge name */
839             bridge->name = br_name_dup;
840             bridge->next = g_monitored_bridge_list_head;
841             g_monitored_bridge_list_head = bridge;
842             pthread_mutex_unlock(&g_stats_lock);
843             DEBUG("%s: found monitored interface \"%s\"", plugin_name, br_name);
844           }
845         }
846       }
847     } else {
848       WARNING("%s: option '%s' not allowed here", plugin_name, child->key);
849       goto cleanup_fail;
850     }
851   }
852   return 0;
853
854 cleanup_fail:
855   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
856   return -1;
857 }
858
859 /* Initialize OvS Stats plugin*/
860 static int ovs_stats_plugin_init(void) {
861   ovs_db_callback_t cb = {.post_conn_init = ovs_stats_initialize,
862                           .post_conn_terminate = ovs_stats_conn_terminate};
863
864   INFO("%s: Connecting to OVS DB using address=%s, service=%s, unix=%s",
865        plugin_name, ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
866        ovs_stats_cfg.ovs_db_unix);
867   /* connect to OvS DB */
868   if ((g_ovs_db =
869            ovs_db_init(ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
870                        ovs_stats_cfg.ovs_db_unix, &cb)) == NULL) {
871     ERROR("%s: plugin: failed to connect to OvS DB server", plugin_name);
872     return -1;
873   }
874   int err = pthread_mutex_init(&g_stats_lock, NULL);
875   if (err < 0) {
876     ERROR("%s: plugin: failed to initialize cache lock", plugin_name);
877     ovs_db_destroy(g_ovs_db);
878     return -1;
879   }
880   return 0;
881 }
882
883 /* OvS stats read callback. Read bridge/port information and submit it*/
884 static int ovs_stats_plugin_read(__attribute__((unused)) user_data_t *ud) {
885   bridge_list_t *bridge;
886   port_list_t *port;
887   char devname[PORT_NAME_SIZE_MAX * 2];
888
889   pthread_mutex_lock(&g_stats_lock);
890   for (bridge = g_bridge_list_head; bridge != NULL; bridge = bridge->next) {
891     if (ovs_stats_is_monitored_bridge(bridge->name)) {
892       for (port = g_port_list_head; port != NULL; port = port->next)
893         if (port->br == bridge) {
894           if (strlen(port->name) == 0)
895             /* Skip port w/o name. This is possible when read callback
896              * is called after Interface Table update callback but before
897              * Port table Update callback. Will add this port on next read */
898             continue;
899           meta_data_t *meta = meta_data_create();
900           if (meta != NULL) {
901             meta_data_add_string(meta, "uuid", port->iface_uuid);
902             if (strlen(port->ex_vm_id))
903               meta_data_add_string(meta, "vm-uuid", port->ex_vm_id);
904             if (strlen(port->ex_iface_id))
905               meta_data_add_string(meta, "iface-id", port->ex_iface_id);
906           }
907           snprintf(devname, sizeof(devname), "%s.%s", bridge->name, port->name);
908           ovs_stats_submit_one(devname, "if_collisions", NULL,
909                                port->stats[collisions], meta);
910           ovs_stats_submit_two(devname, "if_dropped", NULL,
911                                port->stats[rx_dropped], port->stats[tx_dropped],
912                                meta);
913           ovs_stats_submit_two(devname, "if_errors", NULL,
914                                port->stats[rx_errors], port->stats[tx_errors],
915                                meta);
916           ovs_stats_submit_two(devname, "if_packets", NULL,
917                                port->stats[rx_packets], port->stats[tx_packets],
918                                meta);
919           ovs_stats_submit_one(devname, "if_rx_errors", "crc",
920                                port->stats[rx_crc_err], meta);
921           ovs_stats_submit_one(devname, "if_rx_errors", "frame",
922                                port->stats[rx_frame_err], meta);
923           ovs_stats_submit_one(devname, "if_rx_errors", "over",
924                                port->stats[rx_over_err], meta);
925           ovs_stats_submit_one(devname, "if_rx_octets", NULL,
926                                port->stats[rx_bytes], meta);
927           ovs_stats_submit_one(devname, "if_tx_octets", NULL,
928                                port->stats[tx_bytes], meta);
929           ovs_stats_submit_two(devname, "if_packets", "1_to_64_packets",
930                                port->stats[rx_1_to_64_packets],
931                                port->stats[tx_1_to_64_packets], meta);
932           ovs_stats_submit_two(devname, "if_packets", "65_to_127_packets",
933                                port->stats[rx_65_to_127_packets],
934                                port->stats[tx_65_to_127_packets], meta);
935           ovs_stats_submit_two(devname, "if_packets", "128_to_255_packets",
936                                port->stats[rx_128_to_255_packets],
937                                port->stats[tx_128_to_255_packets], meta);
938           ovs_stats_submit_two(devname, "if_packets", "256_to_511_packets",
939                                port->stats[rx_256_to_511_packets],
940                                port->stats[tx_256_to_511_packets], meta);
941           ovs_stats_submit_two(devname, "if_packets", "512_to_1023_packets",
942                                port->stats[rx_512_to_1023_packets],
943                                port->stats[tx_512_to_1023_packets], meta);
944           ovs_stats_submit_two(devname, "if_packets", "1024_to_1518_packets",
945                                port->stats[rx_1024_to_1522_packets],
946                                port->stats[tx_1024_to_1522_packets], meta);
947           ovs_stats_submit_two(devname, "if_packets", "1523_to_max_packets",
948                                port->stats[rx_1523_to_max_packets],
949                                port->stats[tx_1523_to_max_packets], meta);
950           ovs_stats_submit_two(devname, "if_packets", "broadcast_packets",
951                                port->stats[rx_broadcast_packets],
952                                port->stats[tx_broadcast_packets], meta);
953           ovs_stats_submit_one(devname, "if_multicast", "tx_multicast_packets",
954                                port->stats[tx_multicast_packets], meta);
955           ovs_stats_submit_one(devname, "if_rx_errors", "rx_undersized_errors",
956                                port->stats[rx_undersized_errors], meta);
957           ovs_stats_submit_one(devname, "if_rx_errors", "rx_oversize_errors",
958                                port->stats[rx_oversize_errors], meta);
959           ovs_stats_submit_one(devname, "if_rx_errors", "rx_fragmented_errors",
960                                port->stats[rx_fragmented_errors], meta);
961           ovs_stats_submit_one(devname, "if_rx_errors", "rx_jabber_errors",
962                                port->stats[rx_jabber_errors], meta);
963
964           meta_data_destroy(meta);
965         }
966     } else
967       continue;
968   }
969   pthread_mutex_unlock(&g_stats_lock);
970   return 0;
971 }
972
973 /* Shutdown OvS Stats plugin */
974 static int ovs_stats_plugin_shutdown(void) {
975   pthread_mutex_lock(&g_stats_lock);
976   DEBUG("OvS Statistics plugin shutting down");
977   ovs_db_destroy(g_ovs_db);
978   ovs_stats_free_bridge_list(g_bridge_list_head);
979   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
980   ovs_stats_free_port_list(g_port_list_head);
981   pthread_mutex_unlock(&g_stats_lock);
982   pthread_mutex_destroy(&g_stats_lock);
983   return 0;
984 }
985
986 /* Register OvS Stats plugin callbacks */
987 void module_register(void) {
988   plugin_register_complex_config(plugin_name, ovs_stats_plugin_config);
989   plugin_register_init(plugin_name, ovs_stats_plugin_init);
990   plugin_register_complex_read(NULL, plugin_name, ovs_stats_plugin_read, 0,
991                                NULL);
992   plugin_register_shutdown(plugin_name, ovs_stats_plugin_shutdown);
993 }