ovs_events: Fix notification metadata garbage.
[collectd.git] / src / ovs_events.c
1 /**
2  * collectd - src/ovs_events.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 "collectd.h"
29
30 #include "common.h" /* auxiliary functions */
31
32 #include "utils_ovs.h" /* OVS helpers */
33
34 #define OVS_EVENTS_IFACE_NAME_SIZE 128
35 #define OVS_EVENTS_IFACE_UUID_SIZE 64
36 #define OVS_EVENTS_EXT_IFACE_ID_SIZE 64
37 #define OVS_EVENTS_EXT_VM_UUID_SIZE 64
38 #define OVS_EVENTS_PLUGIN "ovs_events"
39 #define OVS_EVENTS_CTX_LOCK                                                    \
40   for (int __i = ovs_events_ctx_lock(); __i != 0; __i = ovs_events_ctx_unlock())
41 #define OVS_EVENTS_CONFIG_ERROR(option)                                        \
42   do {                                                                         \
43     ERROR(OVS_EVENTS_PLUGIN ": read '%s' config option failed", option);       \
44     goto failure;                                                              \
45   } while (0)
46
47 /* Link status type */
48 enum ovs_events_link_status_e { DOWN, UP };
49 typedef enum ovs_events_link_status_e ovs_events_link_status_t;
50
51 /* Interface info */
52 struct ovs_events_iface_info_s {
53   char name[OVS_EVENTS_IFACE_NAME_SIZE];           /* interface name */
54   char uuid[OVS_EVENTS_IFACE_UUID_SIZE];           /* interface UUID */
55   char ext_iface_id[OVS_EVENTS_EXT_IFACE_ID_SIZE]; /* external interface id */
56   char ext_vm_uuid[OVS_EVENTS_EXT_VM_UUID_SIZE];   /* external VM UUID */
57   ovs_events_link_status_t link_status;            /* interface link status */
58   struct ovs_events_iface_info_s *next;            /* next interface info */
59 };
60 typedef struct ovs_events_iface_info_s ovs_events_iface_info_t;
61
62 /* Interface list */
63 struct ovs_events_iface_list_s {
64   char name[OVS_EVENTS_IFACE_NAME_SIZE]; /* interface name */
65   struct ovs_events_iface_list_s *next;  /* next interface info */
66 };
67 typedef struct ovs_events_iface_list_s ovs_events_iface_list_t;
68
69 /* OVS events configuration data */
70 struct ovs_events_config_s {
71   _Bool send_notification;                 /* sent notification to collectd? */
72   char ovs_db_node[OVS_DB_ADDR_NODE_SIZE]; /* OVS DB node */
73   char ovs_db_serv[OVS_DB_ADDR_SERVICE_SIZE]; /* OVS DB service */
74   char ovs_db_unix[OVS_DB_ADDR_UNIX_SIZE];    /* OVS DB unix socket path */
75   ovs_events_iface_list_t *ifaces;            /* interface info */
76 };
77 typedef struct ovs_events_config_s ovs_events_config_t;
78
79 /* OVS events context type */
80 struct ovs_events_ctx_s {
81   pthread_mutex_t mutex;      /* mutex to lock the context */
82   ovs_db_t *ovs_db;           /* pointer to OVS DB instance */
83   ovs_events_config_t config; /* plugin config */
84   char *ovs_db_select_params; /* OVS DB select parameter request */
85   _Bool is_db_available;      /* specify whether OVS DB is available */
86 };
87 typedef struct ovs_events_ctx_s ovs_events_ctx_t;
88
89 /*
90  * Private variables
91  */
92 static ovs_events_ctx_t ovs_events_ctx = {
93     .mutex = PTHREAD_MUTEX_INITIALIZER,
94     .config = {.send_notification = 0,     /* do not send notification */
95                .ovs_db_node = "localhost", /* use default OVS DB node */
96                .ovs_db_serv = "6640",      /* use default OVS DB service */
97                .ovs_db_unix = "",          /* UNIX path empty by default */
98                .ifaces = NULL},
99     .ovs_db_select_params = NULL,
100     .is_db_available = 0,
101     .ovs_db = NULL};
102
103 /* This function is used only by "OVS_EVENTS_CTX_LOCK" define (see above).
104  * It always returns 1 when context is locked.
105  */
106 static int ovs_events_ctx_lock() {
107   pthread_mutex_lock(&ovs_events_ctx.mutex);
108   return (1);
109 }
110
111 /* This function is used only by "OVS_EVENTS_CTX_LOCK" define (see above).
112  * It always returns 0 when context is unlocked.
113  */
114 static int ovs_events_ctx_unlock() {
115   pthread_mutex_unlock(&ovs_events_ctx.mutex);
116   return (0);
117 }
118
119 /* Check if given interface name exists in configuration file. It
120  * returns 1 if exists otherwise 0. If no interfaces are configured,
121  * -1 is returned
122  */
123 static int ovs_events_config_iface_exists(const char *ifname) {
124   if (ovs_events_ctx.config.ifaces == NULL)
125     return (-1);
126
127   /* check if given interface exists */
128   for (ovs_events_iface_list_t *iface = ovs_events_ctx.config.ifaces; iface;
129        iface = iface->next)
130     if (strcmp(ifname, iface->name) == 0)
131       return (1);
132
133   return (0);
134 }
135
136 /* Get OVS DB select parameter request based on rfc7047,
137  * "Transact" & "Select" section
138  */
139 static char *ovs_events_get_select_params() {
140   int ret = 0;
141   size_t buff_size = 0;
142   size_t buff_off = 0;
143   char *opt_buff = NULL;
144   const char params_fmt[] = "[\"Open_vSwitch\"%s]";
145   const char option_fmt[] = ",{\"op\":\"select\",\"table\":\"Interface\","
146                             "\"where\":[[\"name\",\"==\",\"%s\"]],"
147                             "\"columns\":[\"link_state\",\"external_ids\","
148                             "\"name\",\"_uuid\"]}";
149   const char default_opt[] = ",{\"op\":\"select\",\"table\":\"Interface\","
150                              "\"where\":[],\"columns\":[\"link_state\","
151                              "\"external_ids\",\"name\",\"_uuid\"]}";
152   /* setup OVS DB interface condition */
153   for (ovs_events_iface_list_t *iface = ovs_events_ctx.config.ifaces; iface;
154        iface = iface->next, buff_off += ret) {
155     /* allocate new buffer (format size + ifname len is good enough) */
156     buff_size += (sizeof(option_fmt) + strlen(iface->name));
157     char *new_buff = realloc(opt_buff, buff_size);
158     if (new_buff == NULL) {
159       sfree(opt_buff);
160       return NULL;
161     }
162     opt_buff = new_buff;
163     ret = ssnprintf(opt_buff + buff_off, buff_size - buff_off, option_fmt,
164                     iface->name);
165     if (ret < 0) {
166       sfree(opt_buff);
167       return NULL;
168     }
169   }
170   /* if no interfaces are configured, use default params */
171   if (opt_buff == NULL)
172     opt_buff = strdup(default_opt);
173
174   /* allocate memory for OVS DB select params */
175   size_t params_size = sizeof(params_fmt) + strlen(opt_buff);
176   char *params_buff = malloc(params_size);
177   if (params_buff == NULL) {
178     sfree(opt_buff);
179     return NULL;
180   }
181
182   /* create OVS DB select params */
183   if (ssnprintf(params_buff, params_size, params_fmt, opt_buff) < 0)
184     sfree(params_buff);
185
186   sfree(opt_buff);
187   return params_buff;
188 }
189
190 /* Release memory allocated for configuration data */
191 static void ovs_events_config_free() {
192   ovs_events_iface_list_t *del_iface = NULL;
193   sfree(ovs_events_ctx.ovs_db_select_params);
194   while (ovs_events_ctx.config.ifaces) {
195     del_iface = ovs_events_ctx.config.ifaces;
196     ovs_events_ctx.config.ifaces = ovs_events_ctx.config.ifaces->next;
197     sfree(del_iface);
198   }
199 }
200
201 /* Parse plugin configuration file and store the config
202  * in allocated memory. Returns negative value in case of error.
203  */
204 static int ovs_events_plugin_config(oconfig_item_t *ci) {
205   ovs_events_iface_list_t *new_iface;
206
207   for (int i = 0; i < ci->children_num; i++) {
208     oconfig_item_t *child = ci->children + i;
209     if (strcasecmp("SendNotification", child->key) == 0) {
210       if (cf_util_get_boolean(child,
211                               &ovs_events_ctx.config.send_notification) != 0)
212         OVS_EVENTS_CONFIG_ERROR(child->key);
213     } else if (strcasecmp("Address", child->key) == 0) {
214       if (cf_util_get_string_buffer(
215               child, ovs_events_ctx.config.ovs_db_node,
216               sizeof(ovs_events_ctx.config.ovs_db_node)) != 0)
217         OVS_EVENTS_CONFIG_ERROR(child->key);
218     } else if (strcasecmp("Port", child->key) == 0) {
219       if (cf_util_get_string_buffer(
220               child, ovs_events_ctx.config.ovs_db_serv,
221               sizeof(ovs_events_ctx.config.ovs_db_serv)) != 0)
222         OVS_EVENTS_CONFIG_ERROR(child->key);
223     } else if (strcasecmp("Socket", child->key) == 0) {
224       if (cf_util_get_string_buffer(
225               child, ovs_events_ctx.config.ovs_db_unix,
226               sizeof(ovs_events_ctx.config.ovs_db_unix)) != 0)
227         OVS_EVENTS_CONFIG_ERROR(child->key);
228     } else if (strcasecmp("Interfaces", child->key) == 0) {
229       for (int j = 0; j < child->values_num; j++) {
230         /* check value type */
231         if (child->values[j].type != OCONFIG_TYPE_STRING) {
232           ERROR(OVS_EVENTS_PLUGIN
233                 ": given interface name is not a string [idx=%d]",
234                 j);
235           goto failure;
236         }
237         /* allocate memory for configured interface */
238         if ((new_iface = malloc(sizeof(*new_iface))) == NULL) {
239           ERROR(OVS_EVENTS_PLUGIN ": malloc () copy interface name fail");
240           goto failure;
241         } else {
242           /* store interface name */
243           sstrncpy(new_iface->name, child->values[j].value.string,
244                    sizeof(new_iface->name));
245           new_iface->next = ovs_events_ctx.config.ifaces;
246           ovs_events_ctx.config.ifaces = new_iface;
247           DEBUG(OVS_EVENTS_PLUGIN ": found monitored interface \"%s\"",
248                 new_iface->name);
249         }
250       }
251     } else {
252       ERROR(OVS_EVENTS_PLUGIN ": option '%s' is not allowed here", child->key);
253       goto failure;
254     }
255   }
256   return (0);
257
258 failure:
259   ovs_events_config_free();
260   return (-1);
261 }
262
263 /* Dispatch OVS interface link status event to collectd */
264 static void
265 ovs_events_dispatch_notification(const ovs_events_iface_info_t *ifinfo) {
266   const char *msg_link_status = NULL;
267   notification_t n = {
268       NOTIF_FAILURE, cdtime(), "", "", OVS_EVENTS_PLUGIN, "", "", "", NULL};
269
270   /* convert link status to message string */
271   switch (ifinfo->link_status) {
272   case UP:
273     msg_link_status = "UP";
274     n.severity = NOTIF_OKAY;
275     break;
276   case DOWN:
277     msg_link_status = "DOWN";
278     n.severity = NOTIF_WARNING;
279     break;
280   default:
281     ERROR(OVS_EVENTS_PLUGIN ": unknown interface link status");
282     return;
283   }
284
285   /* add interface metadata to the notification */
286   if (plugin_notification_meta_add_string(&n, "uuid", ifinfo->uuid) < 0) {
287     ERROR(OVS_EVENTS_PLUGIN ": add interface uuid meta data failed");
288     return;
289   }
290
291   if (strlen(ifinfo->ext_vm_uuid) > 0)
292     if (plugin_notification_meta_add_string(&n, "vm-uuid",
293                                             ifinfo->ext_vm_uuid) < 0) {
294       ERROR(OVS_EVENTS_PLUGIN ": add interface vm-uuid meta data failed");
295       return;
296     }
297
298   if (strlen(ifinfo->ext_iface_id) > 0)
299     if (plugin_notification_meta_add_string(&n, "iface-id",
300                                             ifinfo->ext_iface_id) < 0) {
301       ERROR(OVS_EVENTS_PLUGIN ": add interface iface-id meta data failed");
302       return;
303     }
304
305   /* fill the notification data */
306   ssnprintf(n.message, sizeof(n.message),
307             "link state of \"%s\" interface has been changed to \"%s\"",
308             ifinfo->name, msg_link_status);
309   sstrncpy(n.host, hostname_g, sizeof(n.host));
310   sstrncpy(n.plugin_instance, ifinfo->name, sizeof(n.plugin_instance));
311   sstrncpy(n.type, "gauge", sizeof(n.type));
312   sstrncpy(n.type_instance, "link_status", sizeof(n.type_instance));
313   plugin_dispatch_notification(&n);
314 }
315
316 /* Dispatch OVS interface link status value to collectd */
317 static void
318 ovs_events_link_status_submit(const ovs_events_iface_info_t *ifinfo) {
319   value_list_t vl = VALUE_LIST_INIT;
320   meta_data_t *meta = NULL;
321
322   /* add interface metadata to the submit value */
323   if ((meta = meta_data_create()) != NULL) {
324     if (meta_data_add_string(meta, "uuid", ifinfo->uuid) < 0)
325       ERROR(OVS_EVENTS_PLUGIN ": add interface uuid meta data failed");
326
327     if (strlen(ifinfo->ext_vm_uuid) > 0)
328       if (meta_data_add_string(meta, "vm-uuid", ifinfo->ext_vm_uuid) < 0)
329         ERROR(OVS_EVENTS_PLUGIN ": add interface vm-uuid meta data failed");
330
331     if (strlen(ifinfo->ext_iface_id) > 0)
332       if (meta_data_add_string(meta, "iface-id", ifinfo->ext_iface_id) < 0)
333         ERROR(OVS_EVENTS_PLUGIN ": add interface iface-id meta data failed");
334     vl.meta = meta;
335   } else
336     ERROR(OVS_EVENTS_PLUGIN ": create metadata failed");
337
338   vl.time = cdtime();
339   vl.values = &(value_t){.gauge = (gauge_t)ifinfo->link_status};
340   vl.values_len = 1;
341   sstrncpy(vl.plugin, OVS_EVENTS_PLUGIN, sizeof(vl.plugin));
342   sstrncpy(vl.plugin_instance, ifinfo->name, sizeof(vl.plugin_instance));
343   sstrncpy(vl.type, "gauge", sizeof(vl.type));
344   sstrncpy(vl.type_instance, "link_status", sizeof(vl.type_instance));
345   plugin_dispatch_values(&vl);
346   meta_data_destroy(meta);
347 }
348
349 /* Dispatch OVS DB terminate connection event to collectd */
350 static void ovs_events_dispatch_terminate_notification(const char *msg) {
351   notification_t n = {
352       NOTIF_FAILURE, cdtime(), "", "", OVS_EVENTS_PLUGIN, "", "", "", NULL};
353   sstrncpy(n.message, msg, sizeof(n.message));
354   sstrncpy(n.host, hostname_g, sizeof(n.host));
355   plugin_dispatch_notification(&n);
356 }
357
358 /* Get OVS DB interface information and stores it into
359  * ovs_events_iface_info_t structure */
360 static int ovs_events_get_iface_info(yajl_val jobject,
361                                      ovs_events_iface_info_t *ifinfo) {
362   yajl_val jexternal_ids = NULL;
363   yajl_val jvalue = NULL;
364   yajl_val juuid = NULL;
365   const char *state = NULL;
366
367   /* check YAJL type */
368   if (!YAJL_IS_OBJECT(jobject))
369     return (-1);
370
371   /* zero the interface info structure */
372   memset(ifinfo, 0, sizeof(*ifinfo));
373
374   /* try to find external_ids, name and link_state fields */
375   jexternal_ids = ovs_utils_get_value_by_key(jobject, "external_ids");
376   if (jexternal_ids == NULL || ifinfo == NULL)
377     return (-1);
378
379   /* get iface-id from external_ids field */
380   jvalue = ovs_utils_get_map_value(jexternal_ids, "iface-id");
381   if (jvalue != NULL && YAJL_IS_STRING(jvalue))
382     sstrncpy(ifinfo->ext_iface_id, YAJL_GET_STRING(jvalue),
383              sizeof(ifinfo->ext_iface_id));
384
385   /* get vm-uuid from external_ids field */
386   jvalue = ovs_utils_get_map_value(jexternal_ids, "vm-uuid");
387   if (jvalue != NULL && YAJL_IS_STRING(jvalue))
388     sstrncpy(ifinfo->ext_vm_uuid, YAJL_GET_STRING(jvalue),
389              sizeof(ifinfo->ext_vm_uuid));
390
391   /* get interface uuid */
392   jvalue = ovs_utils_get_value_by_key(jobject, "_uuid");
393   if (jvalue == NULL || !YAJL_IS_ARRAY(jvalue) ||
394       YAJL_GET_ARRAY(jvalue)->len != 2)
395     return (-1);
396   juuid = YAJL_GET_ARRAY(jvalue)->values[1];
397   if (juuid == NULL || !YAJL_IS_STRING(juuid))
398     return (-1);
399   sstrncpy(ifinfo->uuid, YAJL_GET_STRING(juuid), sizeof(ifinfo->uuid));
400
401   /* get interface name */
402   jvalue = ovs_utils_get_value_by_key(jobject, "name");
403   if (jvalue == NULL || !YAJL_IS_STRING(jvalue))
404     return (-1);
405   sstrncpy(ifinfo->name, YAJL_GET_STRING(jvalue), sizeof(ifinfo->name));
406
407   /* get OVS DB interface link status */
408   jvalue = ovs_utils_get_value_by_key(jobject, "link_state");
409   if (jvalue != NULL && ((state = YAJL_GET_STRING(jvalue)) != NULL)) {
410     /* convert OVS table link state to link status */
411     if (strcmp(state, "up") == 0)
412       ifinfo->link_status = UP;
413     else if (strcmp(state, "down") == 0)
414       ifinfo->link_status = DOWN;
415   }
416   return (0);
417 }
418
419 /* Process OVS DB update table event. It handles link status update event(s)
420  * and dispatches the value(s) to collectd if interface name matches one of
421  * interfaces specified in configuration file.
422  */
423 static void ovs_events_table_update_cb(yajl_val jupdates) {
424   yajl_val jnew_val = NULL;
425   yajl_val jupdate = NULL;
426   yajl_val jrow_update = NULL;
427   ovs_events_iface_info_t ifinfo;
428
429   /* JSON "Interface" table update example:
430    * ---------------------------------
431    * {"Interface":
432    *  {
433    *   "9adf1db2-29ca-4140-ab22-ae347a4484de":
434    *    {
435    *     "new":
436    *      {
437    *       "name":"br0",
438    *       "link_state":"up"
439    *      },
440    *     "old":
441    *      {
442    *       "link_state":"down"
443    *      }
444    *    }
445    *  }
446    * }
447    */
448   if (!YAJL_IS_OBJECT(jupdates) || !(YAJL_GET_OBJECT(jupdates)->len > 0)) {
449     ERROR(OVS_EVENTS_PLUGIN ": unexpected OVS DB update event received");
450     return;
451   }
452   /* verify if this is a table event */
453   jupdate = YAJL_GET_OBJECT(jupdates)->values[0];
454   if (!YAJL_IS_OBJECT(jupdate)) {
455     ERROR(OVS_EVENTS_PLUGIN ": unexpected table update event received");
456     return;
457   }
458   /* go through all row updates  */
459   for (int row_index = 0; row_index < YAJL_GET_OBJECT(jupdate)->len;
460        ++row_index) {
461     jrow_update = YAJL_GET_OBJECT(jupdate)->values[row_index];
462
463     /* check row update */
464     jnew_val = ovs_utils_get_value_by_key(jrow_update, "new");
465     if (jnew_val == NULL) {
466       ERROR(OVS_EVENTS_PLUGIN ": unexpected row update received");
467       return;
468     }
469     /* get OVS DB interface information */
470     if (ovs_events_get_iface_info(jnew_val, &ifinfo) < 0) {
471       ERROR(OVS_EVENTS_PLUGIN
472             " :unexpected interface information data received");
473       return;
474     }
475     if (ovs_events_config_iface_exists(ifinfo.name) != 0) {
476       DEBUG("name=%s, uuid=%s, ext_iface_id=%s, ext_vm_uuid=%s", ifinfo.name,
477             ifinfo.uuid, ifinfo.ext_iface_id, ifinfo.ext_vm_uuid);
478       /* dispatch notification */
479       ovs_events_dispatch_notification(&ifinfo);
480     }
481   }
482 }
483
484 /* OVS DB reply callback. It parses reply, receives
485  * interface information and dispatches the info to
486  * collectd
487  */
488 static void ovs_events_poll_result_cb(yajl_val jresult, yajl_val jerror) {
489   yajl_val *jvalues = NULL;
490   yajl_val jvalue = NULL;
491   ovs_events_iface_info_t ifinfo;
492
493   if (!YAJL_IS_NULL(jerror)) {
494     ERROR(OVS_EVENTS_PLUGIN "error received by OVS DB server");
495     return;
496   }
497
498   /* result should be an array */
499   if (!YAJL_IS_ARRAY(jresult)) {
500     ERROR(OVS_EVENTS_PLUGIN "invalid data (array is expected)");
501     return;
502   }
503
504   /* go through all rows and get interface info */
505   jvalues = YAJL_GET_ARRAY(jresult)->values;
506   for (int i = 0; i < YAJL_GET_ARRAY(jresult)->len; i++) {
507     jvalue = ovs_utils_get_value_by_key(jvalues[i], "rows");
508     if (jvalue == NULL || !YAJL_IS_ARRAY(jvalue)) {
509       ERROR(OVS_EVENTS_PLUGIN "invalid data (array of rows is expected)");
510       return;
511     }
512     /* get interfaces info */
513     for (int j = 0; j < YAJL_GET_ARRAY(jvalue)->len; j++) {
514       if (ovs_events_get_iface_info(YAJL_GET_ARRAY(jvalue)->values[j],
515                                     &ifinfo) < 0) {
516         ERROR(OVS_EVENTS_PLUGIN
517               "unexpected interface information data received");
518         return;
519       }
520       DEBUG("name=%s, uuid=%s, ext_iface_id=%s, ext_vm_uuid=%s", ifinfo.name,
521             ifinfo.uuid, ifinfo.ext_iface_id, ifinfo.ext_vm_uuid);
522       ovs_events_link_status_submit(&ifinfo);
523     }
524   }
525 }
526
527 /* Setup OVS DB table callback. It subscribes to OVS DB 'Interface' table
528  * to receive link status event(s).
529  */
530 static void ovs_events_conn_initialize(ovs_db_t *pdb) {
531   int ret = 0;
532   const char tb_name[] = "Interface";
533   const char *columns[] = {"_uuid", "external_ids", "name", "link_state", NULL};
534
535   /* register update link status event if needed */
536   if (ovs_events_ctx.config.send_notification) {
537     ret = ovs_db_table_cb_register(pdb, tb_name, columns,
538                                    ovs_events_table_update_cb, NULL,
539                                    OVS_DB_TABLE_CB_FLAG_MODIFY);
540     if (ret < 0) {
541       ERROR(OVS_EVENTS_PLUGIN ": register OVS DB update callback failed");
542       return;
543     }
544   }
545   OVS_EVENTS_CTX_LOCK { ovs_events_ctx.is_db_available = 1; }
546   DEBUG(OVS_EVENTS_PLUGIN ": OVS DB connection has been initialized");
547 }
548
549 /* OVS DB terminate connection notification callback */
550 static void ovs_events_conn_terminate() {
551   const char msg[] = "OVS DB connection has been lost";
552   if (ovs_events_ctx.config.send_notification)
553     ovs_events_dispatch_terminate_notification(msg);
554   WARNING(OVS_EVENTS_PLUGIN ": %s", msg);
555   OVS_EVENTS_CTX_LOCK { ovs_events_ctx.is_db_available = 0; }
556 }
557
558 /* Read OVS DB interface link status callback */
559 static int ovs_events_plugin_read(__attribute__((unused)) user_data_t *u) {
560   _Bool is_connected = 0;
561   OVS_EVENTS_CTX_LOCK { is_connected = ovs_events_ctx.is_db_available; }
562   if (is_connected)
563     if (ovs_db_send_request(ovs_events_ctx.ovs_db, "transact",
564                             ovs_events_ctx.ovs_db_select_params,
565                             ovs_events_poll_result_cb) < 0) {
566       ERROR(OVS_EVENTS_PLUGIN ": get interface info failed");
567       return (-1);
568     }
569   return (0);
570 }
571
572 /* Initialize OVS plugin */
573 static int ovs_events_plugin_init(void) {
574   ovs_db_t *ovs_db = NULL;
575   ovs_db_callback_t cb = {.post_conn_init = ovs_events_conn_initialize,
576                           .post_conn_terminate = ovs_events_conn_terminate};
577
578   DEBUG(OVS_EVENTS_PLUGIN ": OVS DB address=%s, service=%s, unix=%s",
579         ovs_events_ctx.config.ovs_db_node, ovs_events_ctx.config.ovs_db_serv,
580         ovs_events_ctx.config.ovs_db_unix);
581
582   /* generate OVS DB select condition based on list on configured interfaces */
583   ovs_events_ctx.ovs_db_select_params = ovs_events_get_select_params();
584   if (ovs_events_ctx.ovs_db_select_params == NULL) {
585     ERROR(OVS_EVENTS_PLUGIN ": fail to get OVS DB select condition");
586     goto ovs_events_failure;
587   }
588
589   /* initialize OVS DB */
590   ovs_db = ovs_db_init(ovs_events_ctx.config.ovs_db_node,
591                        ovs_events_ctx.config.ovs_db_serv,
592                        ovs_events_ctx.config.ovs_db_unix, &cb);
593   if (ovs_db == NULL) {
594     ERROR(OVS_EVENTS_PLUGIN ": fail to connect to OVS DB server");
595     goto ovs_events_failure;
596   }
597
598   /* store OVS DB handler */
599   OVS_EVENTS_CTX_LOCK { ovs_events_ctx.ovs_db = ovs_db; }
600
601   DEBUG(OVS_EVENTS_PLUGIN ": plugin has been initialized");
602   return (0);
603
604 ovs_events_failure:
605   ERROR(OVS_EVENTS_PLUGIN ": plugin initialize failed");
606   /* release allocated memory */
607   ovs_events_config_free();
608   return (-1);
609 }
610
611 /* Shutdown OVS plugin */
612 static int ovs_events_plugin_shutdown(void) {
613   /* destroy OVS DB */
614   if (ovs_db_destroy(ovs_events_ctx.ovs_db))
615     ERROR(OVS_EVENTS_PLUGIN ": OVSDB object destroy failed");
616
617   /* release memory allocated for config */
618   ovs_events_config_free();
619
620   DEBUG(OVS_EVENTS_PLUGIN ": plugin has been destroyed");
621   return (0);
622 }
623
624 /* Register OVS plugin callbacks */
625 void module_register(void) {
626   plugin_register_complex_config(OVS_EVENTS_PLUGIN, ovs_events_plugin_config);
627   plugin_register_init(OVS_EVENTS_PLUGIN, ovs_events_plugin_init);
628   plugin_register_complex_read(NULL, OVS_EVENTS_PLUGIN, ovs_events_plugin_read,
629                                0, NULL);
630   plugin_register_shutdown(OVS_EVENTS_PLUGIN, ovs_events_plugin_shutdown);
631 }