e298ae9aeeb538d5748d022d63619c63620aa59e
[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   ovs_db_t *ovs_db;             /* pointer to OVS DB instance */
62   ovs_link_config_t config;     /* plugin config */
63   ovs_link_interface_info_t *ifaces;    /* interface info */
64 };
65 typedef struct ovs_link_ctx_s ovs_link_ctx_t;
66
67 /*
68  * Private variables
69  */
70 static ovs_link_ctx_t ovs_link_ctx = {
71   .mutex = PTHREAD_MUTEX_INITIALIZER,
72   .config = {
73              .send_notification = 0,    /* do not send notification */
74              .ovs_db_server_url = NULL},        /* use default OVS DB URL */
75   .ovs_db = NULL,
76   .ifaces = NULL};
77
78 /* This function is used only by "OVS_LINK_CTX_LOCK" define (see above).
79  * It always returns 1 when context is locked.
80  */
81 static inline int
82 ovs_link_ctx_lock()
83 {
84   pthread_mutex_lock(&ovs_link_ctx.mutex);
85   return (1);
86 }
87
88 /* This function is used only by "OVS_LINK_CTX_LOCK" define (see above).
89  * It always returns 0 when context is unlocked.
90  */
91 static inline int
92 ovs_link_ctx_unlock()
93 {
94   pthread_mutex_unlock(&ovs_link_ctx.mutex);
95   return (0);
96 }
97
98 /* Update link status in OVS link context (cache) */
99 static void
100 ovs_link_link_status_update(const char *name, ovs_link_link_status_t status)
101 {
102   OVS_LINK_CTX_LOCK {
103     for (ovs_link_interface_info_t *iface = ovs_link_ctx.ifaces; iface;
104          iface = iface->next)
105       if (strcmp(iface->name, name) == 0)
106         iface->link_status = status;
107   }
108 }
109
110 /* Check if given interface name exists in configuration file. It
111  * returns 1 if exists otherwise 0. If no interfaces are configured,
112  * 1 is returned
113  */
114 static int
115 ovs_link_config_iface_exists(const char *ifname)
116 {
117   int rc = 0;
118   OVS_LINK_CTX_LOCK {
119     if (!(rc = (ovs_link_ctx.ifaces == NULL))) {
120       for (ovs_link_interface_info_t *iface = ovs_link_ctx.ifaces; iface;
121            iface = iface->next)
122         if (rc = (strcmp(ifname, iface->name) == 0))
123           break;
124     }
125   }
126   return rc;
127 }
128
129 /* Release memory allocated for configuration data */
130 static void
131 ovs_link_config_free()
132 {
133   ovs_link_interface_info_t *del_iface = NULL;
134   OVS_LINK_CTX_LOCK {
135     sfree(ovs_link_ctx.config.ovs_db_server_url);
136     while (ovs_link_ctx.ifaces) {
137       del_iface = ovs_link_ctx.ifaces;
138       ovs_link_ctx.ifaces = ovs_link_ctx.ifaces->next;
139       free(del_iface->name);
140       free(del_iface);
141     }
142   }
143 }
144
145 /* Parse plugin configuration file and store the config
146  * in allocated memory. Returns negative value in case of error.
147  */
148 static int
149 ovs_link_plugin_config(oconfig_item_t *ci)
150 {
151   ovs_link_interface_info_t *new_iface;
152   char *if_name;
153
154   for (int i = 0; i < ci->children_num; i++) {
155     oconfig_item_t *child = ci->children + i;
156     if (strcasecmp("SendNotification", child->key) == 0) {
157       if (cf_util_get_boolean(child,
158                               &ovs_link_ctx.config.send_notification) < 0)
159         OVS_LINK_CONFIG_ERROR(child->key);
160     } else if (strcasecmp("OvsDbServerUrl", child->key) == 0) {
161       if (cf_util_get_string(child,
162                              &ovs_link_ctx.config.ovs_db_server_url) < 0)
163         OVS_LINK_CONFIG_ERROR(child->key);
164     } else if (strcasecmp("Interfaces", child->key) == 0) {
165       for (int j = 0; j < child->values_num; j++) {
166         /* check value type */
167         if (child->values[j].type != OCONFIG_TYPE_STRING) {
168           ERROR(OVS_LINK_PLUGIN
169                 ": given interface name is not a string [idx=%d]", j);
170           goto failure;
171         }
172         /* get value */
173         if ((if_name = strdup(child->values[j].value.string)) == NULL) {
174           ERROR(OVS_LINK_PLUGIN " strdup() copy interface name fail");
175           goto failure;
176         }
177         if ((new_iface = malloc(sizeof(*new_iface))) == NULL) {
178           ERROR(OVS_LINK_PLUGIN ": malloc () copy interface name fail");
179           goto failure;
180         } else {
181           /* store interface name */
182           new_iface->name = if_name;
183           new_iface->link_status = UNKNOWN;
184           new_iface->next = ovs_link_ctx.ifaces;
185           ovs_link_ctx.ifaces = new_iface;
186           DEBUG(OVS_LINK_PLUGIN ": found monitored interface \"%s\"",
187                 if_name);
188         }
189       }
190     } else {
191       ERROR(OVS_LINK_PLUGIN ": option '%s' is not allowed here", child->key);
192       goto failure;
193     }
194   }
195   return (0);
196
197 failure:
198   ovs_link_config_free();
199   return (-1);
200 }
201
202 /* Dispatch OVS interface link status event to collectd */
203 static int
204 ovs_link_dispatch_notification(const char *link_name,
205                                ovs_link_link_status_t link_status)
206 {
207   const char *msg_link_status = NULL;
208   notification_t n = {NOTIF_FAILURE, cdtime(), "", "", OVS_LINK_PLUGIN,
209                       "", "", "", NULL};
210
211   /* convert link status to message string */
212   switch (link_status) {
213   case UP:
214     msg_link_status = "UP";
215     n.severity = NOTIF_OKAY;
216     break;
217   case DOWN:
218     msg_link_status = "DOWN";
219     n.severity = NOTIF_WARNING;
220     break;
221   default:
222     msg_link_status = "UNKNOWN";;
223     break;
224   }
225
226   /* fill the notification data */
227   ssnprintf(n.message, sizeof(n.message),
228             "link state of \"%s\" interface has been changed to \"%s\"",
229             link_name, msg_link_status);
230   sstrncpy(n.host, hostname_g, sizeof(n.host));
231   sstrncpy(n.plugin_instance, link_name, sizeof(n.plugin_instance));
232   sstrncpy(n.type, "gauge", sizeof(n.type));
233   sstrncpy(n.type_instance, "link_status", sizeof(n.type_instance));
234   return plugin_dispatch_notification(&n);
235 }
236
237 /* Dispatch OVS interface link status value to collectd */
238 static void
239 ovs_link_link_status_submit(const char *link_name,
240                             ovs_link_link_status_t link_status)
241 {
242   value_t values[1];
243   value_list_t vl = VALUE_LIST_INIT;
244
245   values[0].gauge = (gauge_t) link_status;
246   vl.time = cdtime();
247   vl.values = values;
248   vl.values_len = sizeof(values) / sizeof(values[0]);
249   sstrncpy(vl.host, hostname_g, sizeof(vl.host));
250   sstrncpy(vl.plugin, OVS_LINK_PLUGIN, sizeof(vl.plugin));
251   sstrncpy(vl.plugin_instance, link_name, sizeof(vl.plugin_instance));
252   sstrncpy(vl.type, "gauge", sizeof(vl.type));
253   sstrncpy(vl.type_instance, "link_status", sizeof(vl.type_instance));
254   plugin_dispatch_values(&vl);
255 }
256
257 /* Process OVS DB update table event. It handles link status update event(s)
258  * and dispatches the value(s) to collectd if interface name matches one of
259  * interfaces specified in configuration file.
260  */
261 static void
262 ovs_link_table_update_cb(yajl_val jupdates)
263 {
264   yajl_val jnew_val = NULL;
265   yajl_val jupdate = NULL;
266   yajl_val jrow_update = NULL;
267   yajl_val jlink_name = NULL;
268   yajl_val jlink_state = NULL;
269   const char *link_name = NULL;
270   const char *link_state = NULL;
271   ovs_link_link_status_t link_status = UNKNOWN;
272
273   /* JSON "Interface" table update example:
274    * ---------------------------------
275    * {"Interface":
276    *  {
277    *   "9adf1db2-29ca-4140-ab22-ae347a4484de":
278    *    {
279    *     "new":
280    *      {
281    *       "name":"br0",
282    *       "link_state":"up"
283    *      },
284    *     "old":
285    *      {
286    *       "link_state":"down"
287    *      }
288    *    }
289    *  }
290    * }
291    */
292   if (!YAJL_IS_OBJECT(jupdates) || !(YAJL_GET_OBJECT(jupdates)->len > 0)) {
293     ERROR(OVS_LINK_PLUGIN ": unexpected OVS DB update event received");
294     return;
295   }
296   /* verify if this is a table event */
297   jupdate = YAJL_GET_OBJECT(jupdates)->values[0];
298   if (!YAJL_IS_OBJECT(jupdate)) {
299     ERROR(OVS_LINK_PLUGIN ": unexpected table update event received");
300     return;
301   }
302   /* go through all row updates  */
303   for (int row_index = 0; row_index < YAJL_GET_OBJECT(jupdate)->len;
304        ++row_index) {
305     jrow_update = YAJL_GET_OBJECT(jupdate)->values[row_index];
306
307     /* check row update */
308     jnew_val = ovs_utils_get_value_by_key(jrow_update, "new");
309     if (jnew_val == NULL) {
310       ERROR(OVS_LINK_PLUGIN ": unexpected row update received");
311       return;
312     }
313     /* get link status update */
314     jlink_name = ovs_utils_get_value_by_key(jnew_val, "name");
315     jlink_state = ovs_utils_get_value_by_key(jnew_val, "link_state");
316     if (jlink_name && jlink_state) {
317       link_name = YAJL_GET_STRING(jlink_name);
318       if (link_name && ovs_link_config_iface_exists(link_name)) {
319         /* convert OVS table link state to link status */
320         if (YAJL_IS_STRING(jlink_state)) {
321           link_state = YAJL_GET_STRING(jlink_state);
322           if (strcmp(link_state, "up") == 0)
323             link_status = UP;
324           else if (strcmp(link_state, "down") == 0)
325             link_status = DOWN;
326         }
327         /* update link status in cache */
328         ovs_link_link_status_update(link_name, link_status);
329         if (ovs_link_ctx.config.send_notification)
330           /* dispatch notification */
331           ovs_link_dispatch_notification(link_name, link_status);
332       }
333     }
334   }
335 }
336
337 /* Process OVS DB result table callback. It handles init link status value
338  * and dispatches the value(s) to collectd. The logic to handle init status
339  * is same as 'ovs_link_table_update_cb'.
340  */
341 static void
342 ovs_link_table_result_cb(yajl_val jresult, yajl_val jerror)
343 {
344   (void)jerror;
345   /* jerror is not used as it is the same all the time
346      (rfc7047, "Monitor" section, return value) */
347   ovs_link_table_update_cb(jresult);
348 }
349
350 /* Setup OVS DB table callback. It subscribes to OVS DB 'Interface' table
351  * to receive link status events.
352  */
353 static void
354 ovs_link_initialize(ovs_db_t *pdb)
355 {
356   int ret = 0;
357   const char tb_name[] = "Interface";
358   const char *columns[] = {"name", "link_state", NULL};
359
360   /* register the update callback */
361   ret = ovs_db_table_cb_register(pdb, tb_name, columns,
362                                  ovs_link_table_update_cb,
363                                  ovs_link_table_result_cb,
364                                  OVS_DB_TABLE_CB_FLAG_MODIFY |
365                                  OVS_DB_TABLE_CB_FLAG_INITIAL);
366   if (ret < 0) {
367     ERROR(OVS_LINK_PLUGIN ": register OVS DB update callback failed");
368     return;
369   }
370
371   DEBUG(OVS_LINK_PLUGIN ": OVS DB has been initialized");
372 }
373
374 /* Read OVS link status plugin callback */
375 static int
376 ovs_link_plugin_read(user_data_t *ud)
377 {
378   (void)ud;                     /* unused argument */
379   OVS_LINK_CTX_LOCK {
380     for (ovs_link_interface_info_t *iface = ovs_link_ctx.ifaces; iface;
381          iface = iface->next)
382       /* submit link status value */
383       ovs_link_link_status_submit(iface->name, iface->link_status);
384   }
385   return (0);
386 }
387
388 /* Initialize OVS plugin */
389 static int
390 ovs_link_plugin_init(void)
391 {
392   ovs_db_t *ovs_db = NULL;
393   ovs_db_callback_t cb = {.init_cb = ovs_link_initialize};
394
395   /* set default OVS DB url */
396   if (ovs_link_ctx.config.ovs_db_server_url == NULL)
397     if ((ovs_link_ctx.config.ovs_db_server_url =
398          strdup(OVS_LINK_DEFAULT_OVS_DB_SERVER_URL)) == NULL) {
399       ERROR(OVS_LINK_PLUGIN ": fail to set default OVS DB URL");
400       ovs_link_config_free();
401       return (-1);
402     }
403   DEBUG(OVS_LINK_PLUGIN ": OVS DB url = %s",
404         ovs_link_ctx.config.ovs_db_server_url);
405
406   /* initialize OVS DB */
407   ovs_db = ovs_db_init(ovs_link_ctx.config.ovs_db_server_url, &cb);
408   if (ovs_db == NULL) {
409     ERROR(OVS_LINK_PLUGIN ": fail to connect to OVS DB server");
410     ovs_link_config_free();
411     return (-1);
412   }
413
414   /* store OVS DB handler */
415   OVS_LINK_CTX_LOCK {
416     ovs_link_ctx.ovs_db = ovs_db;
417   }
418
419   DEBUG(OVS_LINK_PLUGIN ": plugin has been initialized");
420   return (0);
421 }
422
423 /* Shutdown OVS plugin */
424 static int
425 ovs_link_plugin_shutdown(void)
426 {
427   /* release memory allocated for config */
428   ovs_link_config_free();
429
430   /* destroy OVS DB */
431   if (ovs_db_destroy(ovs_link_ctx.ovs_db))
432     ERROR(OVS_LINK_PLUGIN ": OVSDB object destroy failed");
433
434   DEBUG(OVS_LINK_PLUGIN ": plugin has been destroyed");
435   return (0);
436 }
437
438 /* Register OVS plugin callbacks */
439 void
440 module_register(void)
441 {
442   plugin_register_complex_config(OVS_LINK_PLUGIN, ovs_link_plugin_config);
443   plugin_register_init(OVS_LINK_PLUGIN, ovs_link_plugin_init);
444   plugin_register_complex_read(NULL, OVS_LINK_PLUGIN, ovs_link_plugin_read,
445                                0, NULL);
446   plugin_register_shutdown(OVS_LINK_PLUGIN, ovs_link_plugin_shutdown);
447 }