ovs_stats: fix potential NULL-string dereference
[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   if (uuid == NULL)
248     return NULL;
249
250   port_list_t *port = ovs_stats_get_port(uuid);
251
252   if (port == NULL) {
253     port = (port_list_t *)calloc(1, sizeof(port_list_t));
254     if (!port) {
255       ERROR("%s: Error allocating port", plugin_name);
256       return NULL;
257     }
258     memset(port->stats, -1, sizeof(int64_t[IFACE_COUNTER_COUNT]));
259     sstrncpy(port->port_uuid, uuid, sizeof(port->port_uuid));
260     pthread_mutex_lock(&g_stats_lock);
261     port->next = g_port_list_head;
262     g_port_list_head = port;
263     pthread_mutex_unlock(&g_stats_lock);
264   }
265   if (bridge != NULL) {
266     pthread_mutex_lock(&g_stats_lock);
267     port->br = bridge;
268     pthread_mutex_unlock(&g_stats_lock);
269   }
270   return port;
271 }
272
273 /* Get bridge by name*/
274 static bridge_list_t *ovs_stats_get_bridge(bridge_list_t *head,
275                                            const char *name) {
276   if (name == NULL)
277     return NULL;
278
279   for (bridge_list_t *bridge = head; bridge != NULL; bridge = bridge->next) {
280     if ((strncmp(bridge->name, name, strlen(bridge->name)) == 0) &&
281         strlen(name) == strlen(bridge->name))
282       return bridge;
283   }
284   return NULL;
285 }
286
287 /* Delete bridge */
288 static int ovs_stats_del_bridge(yajl_val bridge) {
289   const char *old[] = {"old", NULL};
290   const char *name[] = {"name", NULL};
291
292   yajl_val row;
293
294   if (bridge && YAJL_IS_OBJECT(bridge)) {
295     row = yajl_tree_get(bridge, old, yajl_t_object);
296     if (row && YAJL_IS_OBJECT(row)) {
297       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
298       if (br_name && YAJL_IS_STRING(br_name)) {
299         bridge_list_t *prev_br = g_bridge_list_head;
300         for (bridge_list_t *br = g_bridge_list_head; br != NULL;
301              prev_br = br, br = br->next) {
302           if ((strncmp(br->name, br_name->u.string, strlen(br->name)) == 0) &&
303               strlen(br->name) == strlen(br_name->u.string)) {
304             if (br == g_bridge_list_head)
305               g_bridge_list_head = br->next;
306             else
307               prev_br->next = br->next;
308             sfree(br->name);
309             sfree(br);
310             break;
311           }
312         }
313       }
314     }
315   } else
316     WARNING("%s: Incorrect data for deleting bridge", plugin_name);
317   return 0;
318 }
319
320 /* Update Bridge. Create bridge ports*/
321 static int ovs_stats_update_bridge(yajl_val bridge) {
322   const char *new[] = {"new", NULL};
323   const char *name[] = {"name", NULL};
324   const char *ports[] = {"ports", NULL};
325   bridge_list_t *br = NULL;
326
327   if (bridge && YAJL_IS_OBJECT(bridge)) {
328     yajl_val row = yajl_tree_get(bridge, new, yajl_t_object);
329     if (row && YAJL_IS_OBJECT(row)) {
330       yajl_val br_name = yajl_tree_get(row, name, yajl_t_string);
331       yajl_val br_ports = yajl_tree_get(row, ports, yajl_t_array);
332       if (br_name && YAJL_IS_STRING(br_name)) {
333         br = ovs_stats_get_bridge(g_bridge_list_head, YAJL_GET_STRING(br_name));
334         pthread_mutex_lock(&g_stats_lock);
335         if (br == NULL) {
336           br = calloc(1, sizeof(*br));
337           if (!br) {
338             pthread_mutex_unlock(&g_stats_lock);
339             ERROR("%s: calloc(%zu) failed.", plugin_name, sizeof(*br));
340             return -1;
341           }
342           char *tmp = YAJL_GET_STRING(br_name);
343
344           if (tmp != NULL)
345             br->name = strdup(tmp);
346           if (br->name == NULL) {
347             sfree(br);
348             pthread_mutex_unlock(&g_stats_lock);
349             ERROR("%s: strdup failed.", plugin_name);
350             return -1;
351           }
352           br->next = g_bridge_list_head;
353           g_bridge_list_head = br;
354         }
355         pthread_mutex_unlock(&g_stats_lock);
356       }
357       if (br_ports && YAJL_IS_ARRAY(br_ports)) {
358         char *tmp = YAJL_GET_STRING(br_ports->u.array.values[0]);
359         if (tmp != NULL && strcmp("set", tmp) == 0) {
360           yajl_val *array = YAJL_GET_ARRAY(br_ports)->values;
361           size_t array_len = YAJL_GET_ARRAY(br_ports)->len;
362           if (array != NULL && array_len > 0 && YAJL_IS_ARRAY(array[1])) {
363             yajl_val *ports_arr = YAJL_GET_ARRAY(array[1])->values;
364             size_t ports_num = YAJL_GET_ARRAY(array[1])->len;
365             for (size_t i = 0; i < ports_num && ports_arr != NULL; i++) {
366               tmp = YAJL_GET_STRING(ports_arr[i]->u.array.values[1]);
367               if (tmp != NULL)
368                 ovs_stats_new_port(br, tmp);
369               else
370                 goto failure;
371             }
372           }
373         } else
374           ovs_stats_new_port(br, YAJL_GET_STRING(br_ports->u.array.values[1]));
375       }
376     }
377   } else {
378     goto failure;
379   }
380
381   return 0;
382
383 failure:
384   ERROR("Incorrect JSON Bridge data");
385   return -1;
386 }
387
388 /* Handle JSON with Bridge Table change event */
389 static void ovs_stats_bridge_table_change_cb(yajl_val jupdates) {
390   /* Bridge Table update example JSON data
391     {
392       "Bridge": {
393         "bb1f8965-5775-46d9-b820-236ca8edbedc": {
394           "new": {
395             "name": "br0",
396             "ports": [
397               "set",
398               [
399                 [
400                   "uuid",
401                   "117f1a07-7ef0-458a-865c-ec7fbb85bc01"
402                 ],
403                 [
404                   "uuid",
405                   "12fd8bdc-e950-4281-aaa9-46e185658f79"
406                 ]
407               ]
408             ]
409           }
410         }
411       }
412     }
413    */
414   const char *path[] = {"Bridge", NULL};
415
416   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
417
418   if (bridges && YAJL_IS_OBJECT(bridges)) {
419     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
420       yajl_val bridge = YAJL_GET_OBJECT(bridges)->values[i];
421       ovs_stats_update_bridge(bridge);
422     }
423   }
424 }
425
426 /* Handle Bridge Table delete event */
427 static void ovs_stats_bridge_table_delete_cb(yajl_val jupdates) {
428   const char *path[] = {"Bridge", NULL};
429   yajl_val bridges = yajl_tree_get(jupdates, path, yajl_t_object);
430   yajl_val bridge;
431   if (bridges && YAJL_IS_OBJECT(bridges)) {
432     pthread_mutex_lock(&g_stats_lock);
433     for (size_t i = 0; i < YAJL_GET_OBJECT(bridges)->len; i++) {
434       bridge = YAJL_GET_OBJECT(bridges)->values[i];
435       ovs_stats_del_bridge(bridge);
436     }
437     pthread_mutex_unlock(&g_stats_lock);
438   }
439   return;
440 }
441
442 /* Handle JSON with Bridge table initial values */
443 static void ovs_stats_bridge_table_result_cb(yajl_val jresult,
444                                              yajl_val jerror) {
445   if (YAJL_IS_NULL(jerror))
446     ovs_stats_bridge_table_change_cb(jresult);
447   else
448     ERROR("%s: Error received from OvSDB. Table: Bridge", plugin_name);
449   return;
450 }
451
452 /* Update port name */
453 static int ovs_stats_update_port(const char *uuid, yajl_val port) {
454   const char *new[] = {"new", NULL};
455   const char *name[] = {"name", NULL};
456   yajl_val row;
457   port_list_t *portentry = NULL;
458   if (port && YAJL_IS_OBJECT(port)) {
459     row = yajl_tree_get(port, new, yajl_t_object);
460     if (row && YAJL_IS_OBJECT(row)) {
461       yajl_val port_name = yajl_tree_get(row, name, yajl_t_string);
462       if (port_name && YAJL_IS_STRING(port_name)) {
463         portentry = ovs_stats_get_port(uuid);
464         if (portentry == NULL)
465           portentry = ovs_stats_new_port(NULL, uuid);
466         if (portentry) {
467           pthread_mutex_lock(&g_stats_lock);
468           sstrncpy(portentry->name, YAJL_GET_STRING(port_name),
469                    sizeof(portentry->name));
470           pthread_mutex_unlock(&g_stats_lock);
471         }
472       }
473     }
474   } else {
475     ERROR("Incorrect JSON Port data");
476     return -1;
477   }
478   return 0;
479 }
480
481 /* Delete port from global port list */
482 static int ovs_stats_del_port(const char *uuid) {
483   port_list_t *prev_port = g_port_list_head;
484   for (port_list_t *port = g_port_list_head; port != NULL;
485        prev_port = port, port = port->next) {
486     if (strncmp(port->port_uuid, uuid, strlen(port->port_uuid)) == 0) {
487       if (port == g_port_list_head)
488         g_port_list_head = port->next;
489       else
490         prev_port->next = port->next;
491       sfree(port);
492       break;
493     }
494   }
495   return 0;
496 }
497
498 /* Handle JSON with Port Table change event */
499 static void ovs_stats_port_table_change_cb(yajl_val jupdates) {
500   /* Port Table update example JSON data
501     {
502       "Port": {
503         "ab107d6f-28a1-4257-b1cc-5b742821db8a": {
504           "new": {
505             "name": "br1",
506             "interfaces": [
507               "uuid",
508               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
509             ]
510           }
511         }
512       }
513     }
514    */
515   const char *path[] = {"Port", NULL};
516   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
517   yajl_val port;
518   if (ports && YAJL_IS_OBJECT(ports)) {
519     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
520       port = YAJL_GET_OBJECT(ports)->values[i];
521       ovs_stats_update_port(YAJL_GET_OBJECT(ports)->keys[i], port);
522     }
523   }
524   return;
525 }
526
527 /* Handle JSON with Port table initial values */
528 static void ovs_stats_port_table_result_cb(yajl_val jresult, yajl_val jerror) {
529   if (YAJL_IS_NULL(jerror))
530     ovs_stats_port_table_change_cb(jresult);
531   else
532     ERROR("%s: Error received from OvSDB. Table: Port", plugin_name);
533   return;
534 }
535
536 /* Handle Port Table delete event */
537 static void ovs_stats_port_table_delete_cb(yajl_val jupdates) {
538   const char *path[] = {"Port", NULL};
539   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
540   pthread_mutex_lock(&g_stats_lock);
541   if (ports && YAJL_IS_OBJECT(ports))
542     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++) {
543       ovs_stats_del_port(YAJL_GET_OBJECT(ports)->keys[i]);
544     }
545   pthread_mutex_unlock(&g_stats_lock);
546   return;
547 }
548
549 /* Update interface statistics */
550 static int ovs_stats_update_iface_stats(port_list_t *port, yajl_val stats) {
551   yajl_val stat;
552   iface_counter counter_index = 0;
553   char *counter_name = NULL;
554   int64_t counter_value = 0;
555   if (stats && YAJL_IS_ARRAY(stats))
556     for (size_t i = 0; i < YAJL_GET_ARRAY(stats)->len; i++) {
557       stat = YAJL_GET_ARRAY(stats)->values[i];
558       if (!YAJL_IS_ARRAY(stat))
559         return -1;
560       counter_name = YAJL_GET_STRING(YAJL_GET_ARRAY(stat)->values[0]);
561       counter_index = ovs_stats_counter_name_to_type(counter_name);
562       counter_value = YAJL_GET_INTEGER(YAJL_GET_ARRAY(stat)->values[1]);
563       if (counter_index == not_supported)
564         continue;
565       port->stats[counter_index] = counter_value;
566     }
567
568   return 0;
569 }
570
571 /* Update interface external_ids */
572 static int ovs_stats_update_iface_ext_ids(port_list_t *port, yajl_val ext_ids) {
573   yajl_val ext_id;
574   char *key;
575   char *value;
576
577   if (ext_ids && YAJL_IS_ARRAY(ext_ids))
578     for (size_t i = 0; i < YAJL_GET_ARRAY(ext_ids)->len; i++) {
579       ext_id = YAJL_GET_ARRAY(ext_ids)->values[i];
580       if (!YAJL_IS_ARRAY(ext_id))
581         return -1;
582       key = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[0]);
583       value = YAJL_GET_STRING(YAJL_GET_ARRAY(ext_id)->values[1]);
584       if (key && value) {
585         if (strncmp(key, "iface-id", strlen(key)) == 0)
586           sstrncpy(port->ex_iface_id, value, sizeof(port->ex_iface_id));
587         else if (strncmp(key, "vm-uuid", strlen(key)) == 0)
588           sstrncpy(port->ex_vm_id, value, sizeof(port->ex_vm_id));
589       }
590     }
591
592   return 0;
593 }
594
595 /* Get interface statistic and external_ids */
596 static int ovs_stats_update_iface(yajl_val iface) {
597   if (!iface || !YAJL_IS_OBJECT(iface)) {
598     ERROR("ovs_stats plugin: incorrect JSON port data");
599     return -1;
600   }
601
602   yajl_val row = ovs_utils_get_value_by_key(iface, "new");
603   if (!row || !YAJL_IS_OBJECT(row))
604     return 0;
605
606   yajl_val iface_name = ovs_utils_get_value_by_key(row, "name");
607   if (!iface_name || !YAJL_IS_STRING(iface_name))
608     return 0;
609
610   port_list_t *port = ovs_stats_get_port_by_name(YAJL_GET_STRING(iface_name));
611   if (port == NULL)
612     return 0;
613
614   yajl_val iface_stats = ovs_utils_get_value_by_key(row, "statistics");
615   yajl_val iface_ext_ids = ovs_utils_get_value_by_key(row, "external_ids");
616   yajl_val iface_uuid = ovs_utils_get_value_by_key(row, "_uuid");
617   /*
618    * {
619         "statistics": [
620           "map",
621           [
622             [
623               "collisions",
624               0
625             ],
626             . . .
627             [
628               "tx_packets",
629               0
630             ]
631           ]
632         ]
633       }
634    Check that statistics is an array with 2 elements
635    */
636   if (iface_stats && YAJL_IS_ARRAY(iface_stats) &&
637       YAJL_GET_ARRAY(iface_stats)->len == 2)
638     ovs_stats_update_iface_stats(port, YAJL_GET_ARRAY(iface_stats)->values[1]);
639   if (iface_ext_ids && YAJL_IS_ARRAY(iface_ext_ids))
640     ovs_stats_update_iface_ext_ids(port,
641                                    YAJL_GET_ARRAY(iface_ext_ids)->values[1]);
642   if (iface_uuid && YAJL_IS_ARRAY(iface_uuid) &&
643       YAJL_GET_ARRAY(iface_uuid)->len == 2 &&
644       YAJL_GET_STRING(YAJL_GET_ARRAY(iface_uuid)->values[1]) != NULL)
645     sstrncpy(port->iface_uuid,
646              YAJL_GET_STRING(YAJL_GET_ARRAY(iface_uuid)->values[1]),
647              sizeof(port->iface_uuid));
648   else {
649     ERROR("ovs_stats plugin: incorrect JSON interface data");
650     return -1;
651   }
652
653   return 0;
654 }
655
656 /* Handle JSON with Interface Table change event */
657 static void ovs_stats_interface_table_change_cb(yajl_val jupdates) {
658   /* Interface Table update example JSON data
659     {
660       "Interface": {
661         "33a289a0-1d34-4e46-a3c2-3e4066fbecc6": {
662           "new": {
663             "name": "br1",
664             "statistics": [
665               "map",
666               [
667                 [
668                   "collisions",
669                   0
670                 ],
671                 [
672                   "rx_bytes",
673                   0
674                 ],
675                . . .
676                 [
677                   "tx_packets",
678                   12617
679                 ]
680               ]
681             ],
682             "_uuid": [
683               "uuid",
684               "33a289a0-1d34-4e46-a3c2-3e4066fbecc6"
685             ]
686             "external_ids": [
687                 "map",
688                 [
689                   [
690                     "attached-mac",
691                     "fa:16:3e:7c:1c:4b"
692                   ],
693                   [
694                     "iface-id",
695                     "a61b7e2b-6951-488a-b4c6-6e91343960b2"
696                   ],
697                   [
698                     "iface-status",
699                     "active"
700                   ]
701                 ]
702               ]
703           }
704         }
705       }
706     }
707    */
708   const char *path[] = {"Interface", NULL};
709   yajl_val ports = yajl_tree_get(jupdates, path, yajl_t_object);
710   pthread_mutex_lock(&g_stats_lock);
711   if (ports && YAJL_IS_OBJECT(ports))
712     for (size_t i = 0; i < YAJL_GET_OBJECT(ports)->len; i++)
713       ovs_stats_update_iface(YAJL_GET_OBJECT(ports)->values[i]);
714   pthread_mutex_unlock(&g_stats_lock);
715   return;
716 }
717
718 /* Handle JSON with Interface table initial values */
719 static void ovs_stats_interface_table_result_cb(yajl_val jresult,
720                                                 yajl_val jerror) {
721   if (YAJL_IS_NULL(jerror))
722     ovs_stats_interface_table_change_cb(jresult);
723   else
724     ERROR("%s: Error received from OvSDB. Table: Interface", plugin_name);
725   return;
726 }
727
728 /* Setup OVS DB table callbacks  */
729 static void ovs_stats_initialize(ovs_db_t *pdb) {
730   const char *bridge_columns[] = {"name", "ports", NULL};
731   const char *port_columns[] = {"name", "interfaces", NULL};
732   const char *interface_columns[] = {"name", "statistics", "_uuid",
733                                      "external_ids", NULL};
734
735   /* subscribe to a tables */
736   ovs_db_table_cb_register(
737       pdb, "Bridge", bridge_columns, ovs_stats_bridge_table_change_cb,
738       ovs_stats_bridge_table_result_cb,
739       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
740           OVS_DB_TABLE_CB_FLAG_MODIFY);
741
742   ovs_db_table_cb_register(pdb, "Bridge", bridge_columns,
743                            ovs_stats_bridge_table_delete_cb, NULL,
744                            OVS_DB_TABLE_CB_FLAG_DELETE);
745
746   ovs_db_table_cb_register(
747       pdb, "Port", port_columns, ovs_stats_port_table_change_cb,
748       ovs_stats_port_table_result_cb,
749       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
750           OVS_DB_TABLE_CB_FLAG_MODIFY);
751
752   ovs_db_table_cb_register(pdb, "Port", port_columns,
753                            ovs_stats_port_table_delete_cb, NULL,
754                            OVS_DB_TABLE_CB_FLAG_DELETE);
755
756   ovs_db_table_cb_register(
757       pdb, "Interface", interface_columns, ovs_stats_interface_table_change_cb,
758       ovs_stats_interface_table_result_cb,
759       OVS_DB_TABLE_CB_FLAG_INITIAL | OVS_DB_TABLE_CB_FLAG_INSERT |
760           OVS_DB_TABLE_CB_FLAG_MODIFY);
761 }
762
763 /* Check if bridge is configured to be monitored in config file */
764 static int ovs_stats_is_monitored_bridge(const char *br_name) {
765   /* if no bridges are configured, return true */
766   if (g_monitored_bridge_list_head == NULL)
767     return 1;
768
769   /* check if given bridge exists */
770   if (ovs_stats_get_bridge(g_monitored_bridge_list_head, br_name) != NULL)
771     return 1;
772
773   return 0;
774 }
775
776 /* Delete all ports from port list */
777 static void ovs_stats_free_port_list(port_list_t *head) {
778   for (port_list_t *i = head; i != NULL;) {
779     port_list_t *del = i;
780     i = i->next;
781     sfree(del);
782   }
783 }
784
785 /* Delete all bridges from bridge list */
786 static void ovs_stats_free_bridge_list(bridge_list_t *head) {
787   for (bridge_list_t *i = head; i != NULL;) {
788     bridge_list_t *del = i;
789     i = i->next;
790     sfree(del->name);
791     sfree(del);
792   }
793 }
794
795 /* Handle OVSDB lost connection callback */
796 static void ovs_stats_conn_terminate() {
797   WARNING("Lost connection to OVSDB server");
798   pthread_mutex_lock(&g_stats_lock);
799   ovs_stats_free_bridge_list(g_bridge_list_head);
800   g_bridge_list_head = NULL;
801   ovs_stats_free_port_list(g_port_list_head);
802   g_port_list_head = NULL;
803   pthread_mutex_unlock(&g_stats_lock);
804 }
805
806 /* Parse plugin configuration file and store the config
807  * in allocated memory. Returns negative value in case of error.
808  */
809 static int ovs_stats_plugin_config(oconfig_item_t *ci) {
810   bridge_list_t *bridge;
811
812   for (int i = 0; i < ci->children_num; i++) {
813     oconfig_item_t *child = ci->children + i;
814     if (strcasecmp("Address", child->key) == 0) {
815       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_node,
816                                     OVS_DB_ADDR_NODE_SIZE) != 0) {
817         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
818         return -1;
819       }
820     } else if (strcasecmp("Port", child->key) == 0) {
821       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_serv,
822                                     OVS_DB_ADDR_SERVICE_SIZE) != 0) {
823         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
824         return -1;
825       }
826     } else if (strcasecmp("Socket", child->key) == 0) {
827       if (cf_util_get_string_buffer(child, ovs_stats_cfg.ovs_db_unix,
828                                     OVS_DB_ADDR_UNIX_SIZE) != 0) {
829         ERROR("%s: parse '%s' option failed", plugin_name, child->key);
830         return -1;
831       }
832     } else if (strcasecmp("Bridges", child->key) == 0) {
833       for (int j = 0; j < child->values_num; j++) {
834         /* check value type */
835         if (child->values[j].type != OCONFIG_TYPE_STRING) {
836           ERROR("%s: Wrong bridge name [idx=%d]. "
837                 "Bridge name should be string",
838                 plugin_name, j);
839           goto cleanup_fail;
840         }
841         /* get value */
842         char const *br_name = child->values[j].value.string;
843         if ((bridge = ovs_stats_get_bridge(g_monitored_bridge_list_head,
844                                            br_name)) == NULL) {
845           if ((bridge = calloc(1, sizeof(bridge_list_t))) == NULL) {
846             ERROR("%s: Error allocating memory for bridge", plugin_name);
847             goto cleanup_fail;
848           } else {
849             char *br_name_dup = strdup(br_name);
850             if (br_name_dup == NULL) {
851               ERROR("%s: strdup() copy bridge name fail", plugin_name);
852               goto cleanup_fail;
853             }
854
855             pthread_mutex_lock(&g_stats_lock);
856             /* store bridge name */
857             bridge->name = br_name_dup;
858             bridge->next = g_monitored_bridge_list_head;
859             g_monitored_bridge_list_head = bridge;
860             pthread_mutex_unlock(&g_stats_lock);
861             DEBUG("%s: found monitored interface \"%s\"", plugin_name, br_name);
862           }
863         }
864       }
865     } else {
866       WARNING("%s: option '%s' not allowed here", plugin_name, child->key);
867       goto cleanup_fail;
868     }
869   }
870   return 0;
871
872 cleanup_fail:
873   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
874   return -1;
875 }
876
877 /* Initialize OvS Stats plugin*/
878 static int ovs_stats_plugin_init(void) {
879   ovs_db_callback_t cb = {.post_conn_init = ovs_stats_initialize,
880                           .post_conn_terminate = ovs_stats_conn_terminate};
881
882   INFO("%s: Connecting to OVS DB using address=%s, service=%s, unix=%s",
883        plugin_name, ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
884        ovs_stats_cfg.ovs_db_unix);
885   /* connect to OvS DB */
886   if ((g_ovs_db =
887            ovs_db_init(ovs_stats_cfg.ovs_db_node, ovs_stats_cfg.ovs_db_serv,
888                        ovs_stats_cfg.ovs_db_unix, &cb)) == NULL) {
889     ERROR("%s: plugin: failed to connect to OvS DB server", plugin_name);
890     return -1;
891   }
892   int err = pthread_mutex_init(&g_stats_lock, NULL);
893   if (err < 0) {
894     ERROR("%s: plugin: failed to initialize cache lock", plugin_name);
895     ovs_db_destroy(g_ovs_db);
896     return -1;
897   }
898   return 0;
899 }
900
901 /* OvS stats read callback. Read bridge/port information and submit it*/
902 static int ovs_stats_plugin_read(__attribute__((unused)) user_data_t *ud) {
903   bridge_list_t *bridge;
904   port_list_t *port;
905   char devname[PORT_NAME_SIZE_MAX * 2];
906
907   pthread_mutex_lock(&g_stats_lock);
908   for (bridge = g_bridge_list_head; bridge != NULL; bridge = bridge->next) {
909     if (ovs_stats_is_monitored_bridge(bridge->name)) {
910       for (port = g_port_list_head; port != NULL; port = port->next)
911         if (port->br == bridge) {
912           if (strlen(port->name) == 0)
913             /* Skip port w/o name. This is possible when read callback
914              * is called after Interface Table update callback but before
915              * Port table Update callback. Will add this port on next read */
916             continue;
917           meta_data_t *meta = meta_data_create();
918           if (meta != NULL) {
919             meta_data_add_string(meta, "uuid", port->iface_uuid);
920             if (strlen(port->ex_vm_id))
921               meta_data_add_string(meta, "vm-uuid", port->ex_vm_id);
922             if (strlen(port->ex_iface_id))
923               meta_data_add_string(meta, "iface-id", port->ex_iface_id);
924           }
925           snprintf(devname, sizeof(devname), "%s.%s", bridge->name, port->name);
926           ovs_stats_submit_one(devname, "if_collisions", NULL,
927                                port->stats[collisions], meta);
928           ovs_stats_submit_two(devname, "if_dropped", NULL,
929                                port->stats[rx_dropped], port->stats[tx_dropped],
930                                meta);
931           ovs_stats_submit_two(devname, "if_errors", NULL,
932                                port->stats[rx_errors], port->stats[tx_errors],
933                                meta);
934           ovs_stats_submit_two(devname, "if_packets", NULL,
935                                port->stats[rx_packets], port->stats[tx_packets],
936                                meta);
937           ovs_stats_submit_one(devname, "if_rx_errors", "crc",
938                                port->stats[rx_crc_err], meta);
939           ovs_stats_submit_one(devname, "if_rx_errors", "frame",
940                                port->stats[rx_frame_err], meta);
941           ovs_stats_submit_one(devname, "if_rx_errors", "over",
942                                port->stats[rx_over_err], meta);
943           ovs_stats_submit_one(devname, "if_rx_octets", NULL,
944                                port->stats[rx_bytes], meta);
945           ovs_stats_submit_one(devname, "if_tx_octets", NULL,
946                                port->stats[tx_bytes], meta);
947           ovs_stats_submit_two(devname, "if_packets", "1_to_64_packets",
948                                port->stats[rx_1_to_64_packets],
949                                port->stats[tx_1_to_64_packets], meta);
950           ovs_stats_submit_two(devname, "if_packets", "65_to_127_packets",
951                                port->stats[rx_65_to_127_packets],
952                                port->stats[tx_65_to_127_packets], meta);
953           ovs_stats_submit_two(devname, "if_packets", "128_to_255_packets",
954                                port->stats[rx_128_to_255_packets],
955                                port->stats[tx_128_to_255_packets], meta);
956           ovs_stats_submit_two(devname, "if_packets", "256_to_511_packets",
957                                port->stats[rx_256_to_511_packets],
958                                port->stats[tx_256_to_511_packets], meta);
959           ovs_stats_submit_two(devname, "if_packets", "512_to_1023_packets",
960                                port->stats[rx_512_to_1023_packets],
961                                port->stats[tx_512_to_1023_packets], meta);
962           ovs_stats_submit_two(devname, "if_packets", "1024_to_1518_packets",
963                                port->stats[rx_1024_to_1522_packets],
964                                port->stats[tx_1024_to_1522_packets], meta);
965           ovs_stats_submit_two(devname, "if_packets", "1523_to_max_packets",
966                                port->stats[rx_1523_to_max_packets],
967                                port->stats[tx_1523_to_max_packets], meta);
968           ovs_stats_submit_two(devname, "if_packets", "broadcast_packets",
969                                port->stats[rx_broadcast_packets],
970                                port->stats[tx_broadcast_packets], meta);
971           ovs_stats_submit_one(devname, "if_multicast", "tx_multicast_packets",
972                                port->stats[tx_multicast_packets], meta);
973           ovs_stats_submit_one(devname, "if_rx_errors", "rx_undersized_errors",
974                                port->stats[rx_undersized_errors], meta);
975           ovs_stats_submit_one(devname, "if_rx_errors", "rx_oversize_errors",
976                                port->stats[rx_oversize_errors], meta);
977           ovs_stats_submit_one(devname, "if_rx_errors", "rx_fragmented_errors",
978                                port->stats[rx_fragmented_errors], meta);
979           ovs_stats_submit_one(devname, "if_rx_errors", "rx_jabber_errors",
980                                port->stats[rx_jabber_errors], meta);
981
982           meta_data_destroy(meta);
983         }
984     } else
985       continue;
986   }
987   pthread_mutex_unlock(&g_stats_lock);
988   return 0;
989 }
990
991 /* Shutdown OvS Stats plugin */
992 static int ovs_stats_plugin_shutdown(void) {
993   DEBUG("OvS Statistics plugin shutting down");
994   ovs_db_destroy(g_ovs_db);
995   pthread_mutex_lock(&g_stats_lock);
996   ovs_stats_free_bridge_list(g_bridge_list_head);
997   ovs_stats_free_bridge_list(g_monitored_bridge_list_head);
998   ovs_stats_free_port_list(g_port_list_head);
999   pthread_mutex_unlock(&g_stats_lock);
1000   pthread_mutex_destroy(&g_stats_lock);
1001   return 0;
1002 }
1003
1004 /* Register OvS Stats plugin callbacks */
1005 void module_register(void) {
1006   plugin_register_complex_config(plugin_name, ovs_stats_plugin_config);
1007   plugin_register_init(plugin_name, ovs_stats_plugin_init);
1008   plugin_register_complex_read(NULL, plugin_name, ovs_stats_plugin_read, 0,
1009                                NULL);
1010   plugin_register_shutdown(plugin_name, ovs_stats_plugin_shutdown);
1011 }