1faa8ea0496df227ff3d06c48aa47c964ab882a5
[collectd.git] / src / ovs_link.c
1 /**
2  * collectd - src/ovs_link.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 of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  *
24  * Authors:
25  *   Volodymyr Mytnyk <volodymyrx.mytnyk@intel.com>
26  **/
27
28 #include "common.h"             /* auxiliary functions */
29 #include "utils_ovs.h"          /* OVS helpers */
30
31 #define OVS_LINK_PLUGIN "ovs_link"
32 #define OVS_LINK_DEFAULT_OVS_DB_SERVER_URL "tcp:127.0.0.1:6640"
33 #define OVS_LINK_CTX_LOCK for (int __i = ovs_link_ctx_lock(); __i != 0 ; \
34                                __i = ovs_link_ctx_unlock())
35 #define OVS_LINK_CONFIG_ERROR(option) do { \
36   ERROR(OVS_LINK_PLUGIN ": read '%s' config option failed", option); \
37   goto failure; } while (0)
38
39 /* Link status type */
40 enum ovs_link_link_status_e {DOWN, UP, UNKNOWN};
41 typedef enum ovs_link_link_status_e ovs_link_link_status_t;
42
43 /* Interface info */
44 struct ovs_link_interface_info_s {
45   char *name;                   /* interface name */
46   ovs_link_link_status_t link_status;   /* link status */
47   struct ovs_link_interface_info_s *next;       /* next interface info */
48 };
49 typedef struct ovs_link_interface_info_s ovs_link_interface_info_t;
50
51 /* OVS link configuration data */
52 struct ovs_link_config_s {
53   _Bool send_notification;      /* sent notification to collectd? */
54   char *ovs_db_server_url;      /* OVS DB server URL */
55 };
56 typedef struct ovs_link_config_s ovs_link_config_t;
57
58 /* OVS link context type */
59 struct ovs_link_ctx_s {
60   pthread_mutex_t mutex;        /* mutex to lock the context */
61   pthread_mutexattr_t mutex_attr;       /* context mutex attribute */
62   ovs_db_t *ovs_db;             /* pointer to OVS DB instance */
63   ovs_link_config_t config;     /* plugin config */
64   ovs_link_interface_info_t *ifaces;    /* interface info */
65 };
66 typedef struct ovs_link_ctx_s ovs_link_ctx_t;
67
68 /*
69  * Private variables
70  */
71 static ovs_link_ctx_t ovs_link_ctx = {
72   .mutex = PTHREAD_MUTEX_INITIALIZER,
73   .config = {
74              .send_notification = 0,    /* do not send notification */
75              .ovs_db_server_url = NULL},        /* use default OVS DB URL */
76   .ovs_db = NULL,
77   .ifaces = NULL};
78
79 /* This function is used only by "OVS_LINK_CTX_LOCK" define (see above).
80  * It always returns 1 when context is locked.
81  */
82 static inline int
83 ovs_link_ctx_lock()
84 {
85   pthread_mutex_lock(&ovs_link_ctx.mutex);
86   return (1);
87 }
88
89 /* This function is used only by "OVS_LINK_CTX_LOCK" define (see above).
90  * It always returns 0 when context is unlocked.
91  */
92 static inline int
93 ovs_link_ctx_unlock()
94 {
95   pthread_mutex_unlock(&ovs_link_ctx.mutex);
96   return (0);
97 }
98
99 /* Update link status in OVS link context (cache) */
100 static void
101 ovs_link_link_status_update(const char *name, ovs_link_link_status_t status)
102 {
103   OVS_LINK_CTX_LOCK {
104     for (ovs_link_interface_info_t *iface = ovs_link_ctx.ifaces; iface;
105          iface = iface->next)
106       if (strcmp(iface->name, name) == 0)
107         iface->link_status = status;
108   }
109 }
110
111 /* Check if given interface name exists in configuration file. It
112  * returns 1 if exists otherwise 0. If no interfaces are configured,
113  * 1 is returned
114  */
115 static int
116 ovs_link_config_iface_exists(const char *ifname)
117 {
118   int rc = 0;
119   OVS_LINK_CTX_LOCK {
120     if (!(rc = (ovs_link_ctx.ifaces == NULL))) {
121       for (ovs_link_interface_info_t *iface = ovs_link_ctx.ifaces; iface;
122            iface = iface->next)
123         if (rc = (strcmp(ifname, iface->name) == 0))
124           break;
125     }
126   }
127   return rc;
128 }
129
130 /* Release memory allocated for configuration data */
131 static void
132 ovs_link_config_free()
133 {
134   ovs_link_interface_info_t *del_iface = NULL;
135   OVS_LINK_CTX_LOCK {
136     sfree(ovs_link_ctx.config.ovs_db_server_url);
137     while (ovs_link_ctx.ifaces) {
138       del_iface = ovs_link_ctx.ifaces;
139       ovs_link_ctx.ifaces = ovs_link_ctx.ifaces->next;
140       free(del_iface->name);
141       free(del_iface);
142     }
143   }
144 }
145
146 /* Parse plugin configuration file and store the config
147  * in allocated memory. Returns negative value in case of error.
148  */
149 static int
150 ovs_link_plugin_config(oconfig_item_t *ci)
151 {
152   ovs_link_interface_info_t *new_iface;
153   char *if_name;
154
155   for (int i = 0; i < ci->children_num; i++) {
156     oconfig_item_t *child = ci->children + i;
157     if (strcasecmp("SendNotification", child->key) == 0) {
158       if (cf_util_get_boolean(child,
159                               &ovs_link_ctx.config.send_notification) < 0)
160         OVS_LINK_CONFIG_ERROR(child->key);
161     } else if (strcasecmp("OvsDbServerUrl", child->key) == 0) {
162       if (cf_util_get_string(child,
163                              &ovs_link_ctx.config.ovs_db_server_url) < 0)
164         OVS_LINK_CONFIG_ERROR(child->key);
165     } else if (strcasecmp("Interfaces", child->key) == 0) {
166       for (int j = 0; j < child->values_num; j++) {
167         /* check value type */
168         if (child->values[j].type != OCONFIG_TYPE_STRING) {
169           ERROR(OVS_LINK_PLUGIN
170                 ": given interface name is not a string [idx=%d]", j);
171           goto failure;
172         }
173         /* get value */
174         if ((if_name = strdup(child->values[j].value.string)) == NULL) {
175           ERROR(OVS_LINK_PLUGIN " strdup() copy interface name fail");
176           goto failure;
177         }
178         if ((new_iface = malloc(sizeof(*new_iface))) == NULL) {
179           ERROR(OVS_LINK_PLUGIN ": malloc () copy interface name fail");
180           goto failure;
181         } else {
182           /* store interface name */
183           new_iface->name = if_name;
184           new_iface->link_status = UNKNOWN;
185           new_iface->next = ovs_link_ctx.ifaces;
186           ovs_link_ctx.ifaces = new_iface;
187           DEBUG(OVS_LINK_PLUGIN ": found monitored interface \"%s\"",
188                 if_name);
189         }
190       }
191     } else {
192       ERROR(OVS_LINK_PLUGIN ": option '%s' is not allowed here", child->key);
193       goto failure;
194     }
195   }
196   return (0);
197
198 failure:
199   ovs_link_config_free();
200   return (-1);
201 }
202
203 /* Dispatch OVS interface link status event to collectd */
204 static int
205 ovs_link_dispatch_notification(const char *link_name,
206                                ovs_link_link_status_t link_status)
207 {
208   const char *msg_link_status = NULL;
209   notification_t n = {NOTIF_FAILURE, cdtime(), "", "", OVS_LINK_PLUGIN,
210                       "", "", "", NULL};
211
212   /* convert link status to message string */
213   switch (link_status) {
214   case UP:
215     msg_link_status = "UP";
216     n.severity = NOTIF_OKAY;
217     break;
218   case DOWN:
219     msg_link_status = "DOWN";
220     n.severity = NOTIF_WARNING;
221     break;
222   default:
223     msg_link_status = "UNKNOWN";;
224     break;
225   }
226
227   /* fill the notification data */
228   ssnprintf(n.message, sizeof(n.message),
229             "link state of \"%s\" interface has been changed to \"%s\"",
230             link_name, msg_link_status);
231   sstrncpy(n.host, hostname_g, sizeof(n.host));
232   sstrncpy(n.plugin_instance, link_name, sizeof(n.plugin_instance));
233   sstrncpy(n.type, "gauge", sizeof(n.type));
234   sstrncpy(n.type_instance, "link_status", sizeof(n.type_instance));
235   return plugin_dispatch_notification(&n);
236 }
237
238 /* Dispatch OVS interface link status value to collectd */
239 static void
240 ovs_link_link_status_submit(const char *link_name,
241                             ovs_link_link_status_t link_status)
242 {
243   value_t values[1];
244   value_list_t vl = VALUE_LIST_INIT;
245
246   values[0].gauge = (gauge_t) link_status;
247   vl.time = cdtime();
248   vl.values = values;
249   vl.values_len = STATIC_ARRAY_SIZE(values);
250   sstrncpy(vl.host, hostname_g, sizeof(vl.host));
251   sstrncpy(vl.plugin, OVS_LINK_PLUGIN, sizeof(vl.plugin));
252   sstrncpy(vl.plugin_instance, link_name, sizeof(vl.plugin_instance));
253   sstrncpy(vl.type, "gauge", sizeof(vl.type));
254   sstrncpy(vl.type_instance, "link_status", sizeof(vl.type_instance));
255   plugin_dispatch_values(&vl);
256 }
257
258 /* Dispatch OVS DB terminate connection event to collectd */
259 static void
260 ovs_link_dispatch_terminate_notification(const char *msg)
261 {
262   notification_t n = {NOTIF_FAILURE, cdtime(), "", "", OVS_LINK_PLUGIN,
263                       "", "", "", NULL};
264   ssnprintf(n.message, sizeof(n.message), msg);
265   sstrncpy(n.host, hostname_g, sizeof(n.host));
266   plugin_dispatch_notification(&n);
267 }
268
269 /* Process OVS DB update table event. It handles link status update event(s)
270  * and dispatches the value(s) to collectd if interface name matches one of
271  * interfaces specified in configuration file.
272  */
273 static void
274 ovs_link_table_update_cb(yajl_val jupdates)
275 {
276   yajl_val jnew_val = NULL;
277   yajl_val jupdate = NULL;
278   yajl_val jrow_update = NULL;
279   yajl_val jlink_name = NULL;
280   yajl_val jlink_state = NULL;
281   const char *link_name = NULL;
282   const char *link_state = NULL;
283   ovs_link_link_status_t link_status = UNKNOWN;
284
285   /* JSON "Interface" table update example:
286    * ---------------------------------
287    * {"Interface":
288    *  {
289    *   "9adf1db2-29ca-4140-ab22-ae347a4484de":
290    *    {
291    *     "new":
292    *      {
293    *       "name":"br0",
294    *       "link_state":"up"
295    *      },
296    *     "old":
297    *      {
298    *       "link_state":"down"
299    *      }
300    *    }
301    *  }
302    * }
303    */
304   if (!YAJL_IS_OBJECT(jupdates) || !(YAJL_GET_OBJECT(jupdates)->len > 0)) {
305     ERROR(OVS_LINK_PLUGIN ": unexpected OVS DB update event received");
306     return;
307   }
308   /* verify if this is a table event */
309   jupdate = YAJL_GET_OBJECT(jupdates)->values[0];
310   if (!YAJL_IS_OBJECT(jupdate)) {
311     ERROR(OVS_LINK_PLUGIN ": unexpected table update event received");
312     return;
313   }
314   /* go through all row updates  */
315   for (int row_index = 0; row_index < YAJL_GET_OBJECT(jupdate)->len;
316        ++row_index) {
317     jrow_update = YAJL_GET_OBJECT(jupdate)->values[row_index];
318
319     /* check row update */
320     jnew_val = ovs_utils_get_value_by_key(jrow_update, "new");
321     if (jnew_val == NULL) {
322       ERROR(OVS_LINK_PLUGIN ": unexpected row update received");
323       return;
324     }
325     /* get link status update */
326     jlink_name = ovs_utils_get_value_by_key(jnew_val, "name");
327     jlink_state = ovs_utils_get_value_by_key(jnew_val, "link_state");
328     if (jlink_name && jlink_state) {
329       link_name = YAJL_GET_STRING(jlink_name);
330       if (link_name && ovs_link_config_iface_exists(link_name)) {
331         /* convert OVS table link state to link status */
332         if (YAJL_IS_STRING(jlink_state)) {
333           link_state = YAJL_GET_STRING(jlink_state);
334           if (strcmp(link_state, "up") == 0)
335             link_status = UP;
336           else if (strcmp(link_state, "down") == 0)
337             link_status = DOWN;
338         }
339         /* update link status in cache */
340         ovs_link_link_status_update(link_name, link_status);
341         if (ovs_link_ctx.config.send_notification)
342           /* dispatch notification */
343           ovs_link_dispatch_notification(link_name, link_status);
344       }
345     }
346   }
347 }
348
349 /* Process OVS DB result table callback. It handles init link status value
350  * and dispatches the value(s) to collectd. The logic to handle init status
351  * is same as 'ovs_link_table_update_cb'.
352  */
353 static void
354 ovs_link_table_result_cb(yajl_val jresult, yajl_val jerror)
355 {
356   (void)jerror;
357   /* jerror is not used as it is the same all the time
358      (rfc7047, "Monitor" section, return value) */
359   ovs_link_table_update_cb(jresult);
360 }
361
362 /* Setup OVS DB table callback. It subscribes to OVS DB 'Interface' table
363  * to receive link status event(s).
364  */
365 static void
366 ovs_link_conn_initialize(ovs_db_t *pdb)
367 {
368   int ret = 0;
369   const char tb_name[] = "Interface";
370   const char *columns[] = {"name", "link_state", NULL};
371
372   /* register the update callback */
373   ret = ovs_db_table_cb_register(pdb, tb_name, columns,
374                                  ovs_link_table_update_cb,
375                                  ovs_link_table_result_cb,
376                                  OVS_DB_TABLE_CB_FLAG_MODIFY |
377                                  OVS_DB_TABLE_CB_FLAG_INITIAL);
378   if (ret < 0) {
379     ERROR(OVS_LINK_PLUGIN ": register OVS DB update callback failed");
380     return;
381   }
382
383   DEBUG(OVS_LINK_PLUGIN ": OVS DB has been initialized");
384 }
385
386 /* OVS DB terminate connection notification callback */
387 static void
388 ovs_link_conn_terminate()
389 {
390   const char msg[] = "OVS DB connection has been lost";
391   if (ovs_link_ctx.config.send_notification)
392     ovs_link_dispatch_terminate_notification(msg);
393   WARNIG(OVS_LINK_PLUGIN ": %s", msg);
394   OVS_LINK_CTX_LOCK {
395     /* update link status to UNKNOWN */
396     for (ovs_link_interface_info_t *iface = ovs_link_ctx.ifaces; iface;
397          iface = iface->next)
398       ovs_link_link_status_update(iface->name, UNKNOWN);
399   }
400 }
401
402 /* Read OVS link status plugin callback */
403 static int
404 ovs_link_plugin_read(user_data_t *ud)
405 {
406   (void)ud;                     /* unused argument */
407   OVS_LINK_CTX_LOCK {
408     for (ovs_link_interface_info_t *iface = ovs_link_ctx.ifaces; iface;
409          iface = iface->next)
410       /* submit link status value */
411       ovs_link_link_status_submit(iface->name, iface->link_status);
412   }
413   return (0);
414 }
415
416 /* Initialize OVS plugin */
417 static int
418 ovs_link_plugin_init(void)
419 {
420   ovs_db_t *ovs_db = NULL;
421   ovs_db_callback_t cb = {.post_conn_init = ovs_link_conn_initialize,
422                           .post_conn_terminate = ovs_link_conn_terminate};
423
424   /* Initialize the context mutex */
425   if (pthread_mutexattr_init(&ovs_link_ctx.mutex_attr) != 0) {
426     ERROR(OVS_LINK_PLUGIN ": init context mutex attribute failed");
427     return (-1);
428   }
429   pthread_mutexattr_settype(&ovs_link_ctx.mutex_attr,
430                             PTHREAD_MUTEX_RECURSIVE);
431   if (pthread_mutex_init(&ovs_link_ctx.mutex, &ovs_link_ctx.mutex_attr) != 0) {
432     ERROR(OVS_LINK_PLUGIN ": init context mutex failed");
433     goto ovs_link_failure;
434   }
435
436   /* set default OVS DB url */
437   if (ovs_link_ctx.config.ovs_db_server_url == NULL)
438     if ((ovs_link_ctx.config.ovs_db_server_url =
439          strdup(OVS_LINK_DEFAULT_OVS_DB_SERVER_URL)) == NULL) {
440       ERROR(OVS_LINK_PLUGIN ": fail to set default OVS DB URL");
441       goto ovs_link_failure;
442     }
443   DEBUG(OVS_LINK_PLUGIN ": OVS DB url = %s",
444         ovs_link_ctx.config.ovs_db_server_url);
445
446   /* initialize OVS DB */
447   ovs_db = ovs_db_init(ovs_link_ctx.config.ovs_db_server_url, &cb);
448   if (ovs_db == NULL) {
449     ERROR(OVS_LINK_PLUGIN ": fail to connect to OVS DB server");
450     goto ovs_link_failure;
451   }
452
453   /* store OVS DB handler */
454   OVS_LINK_CTX_LOCK {
455     ovs_link_ctx.ovs_db = ovs_db;
456   }
457
458   DEBUG(OVS_LINK_PLUGIN ": plugin has been initialized");
459   return (0);
460
461 ovs_link_failure:
462   ERROR(OVS_LINK_PLUGIN ": plugin initialize failed");
463   /* release allocated memory */
464   ovs_link_config_free();
465   /* destroy context mutex */
466   pthread_mutexattr_destroy(&ovs_link_ctx.mutex_attr);
467   pthread_mutex_destroy(&ovs_link_ctx.mutex);
468   return (-1);
469 }
470
471 /* Shutdown OVS plugin */
472 static int
473 ovs_link_plugin_shutdown(void)
474 {
475   /* release memory allocated for config */
476   ovs_link_config_free();
477
478   /* destroy OVS DB */
479   if (ovs_db_destroy(ovs_link_ctx.ovs_db))
480     ERROR(OVS_LINK_PLUGIN ": OVSDB object destroy failed");
481
482   /* destroy context mutex */
483   pthread_mutexattr_destroy(&ovs_link_ctx.mutex_attr);
484   pthread_mutex_destroy(&ovs_link_ctx.mutex);
485
486   DEBUG(OVS_LINK_PLUGIN ": plugin has been destroyed");
487   return (0);
488 }
489
490 /* Register OVS plugin callbacks */
491 void
492 module_register(void)
493 {
494   plugin_register_complex_config(OVS_LINK_PLUGIN, ovs_link_plugin_config);
495   plugin_register_init(OVS_LINK_PLUGIN, ovs_link_plugin_init);
496   plugin_register_complex_read(NULL, OVS_LINK_PLUGIN, ovs_link_plugin_read,
497                                0, NULL);
498   plugin_register_shutdown(OVS_LINK_PLUGIN, ovs_link_plugin_shutdown);
499 }