2 * collectd - src/utils_ovs.c
4 * Copyright(c) 2016 Intel Corporation. All rights reserved.
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
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
13 * so, subject to the following conditions:
15 * The above copyright notice and this permission notice shall be included in
17 * copies or substantial portions of the Software.
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
28 * Volodymyr Mytnyk <volodymyrx.mytnyk@intel.com>
31 /* clang-format off */
33 * OVS DB API internal architecture diagram
34 * +------------------------------------------------------------------------------+
35 * |OVS plugin |OVS utils |
36 * | | +------------------------+ |
37 * | | | echo handler | JSON request/ |
38 * | | +--+ (ovs_db_table_echo_cb) +<---+---------+ update event/ |
39 * | | | | | | | result |
40 * | | | +------------------------+ | | |
41 * | | | | +----+---+--------+ |
42 * | +----------+ | | +------------------------+ | | | | |
43 * | | update | | | | update handler | | | YAJL | JSON | |
44 * | | callback +<-------+(ovs_db_table_update_cp)+<---+ | parser | reader | |
45 * | +----------+ | | | | | | | | |
46 * | | | +------------------------+ | +--------+---+----+ |
48 * | +----------+ | | +------------------------+ | | |
49 * | | result | | | | result handler | | | |
50 * | | callback +<-------+ (ovs_db_result_cb) +<---+ JSON raw | |
51 * | +----------+ | | | | data | |
52 * | | | +------------------------+ | |
54 * | | | +------------------+ +------------+----+ |
55 * | +----------+ | | |thread| | |thread| | |
56 * | | init | | | | | reconnect | | |
57 * | | callback +<---------+ EVENT WORKER +<------------+ POLL WORKER | |
58 * | +----------+ | | +------------------+ +--------+--------+ |
60 * +----------------+-------------------------------------------------------------+
62 * JSON|echo reply raw|data
64 * +-------------------+----------------------------------------------+-----------+
66 * +-------------------------------------------------------------------------------
70 /* collectd headers */
76 #include "utils_ovs.h"
78 /* system libraries */
83 #include <arpa/inet.h>
92 #include <semaphore.h>
94 #define OVS_ERROR(fmt, ...) \
96 ERROR("ovs_utils: " fmt, ##__VA_ARGS__); \
98 #define OVS_DEBUG(fmt, ...) \
100 DEBUG("%s:%d:%s(): " fmt, __FILE__, __LINE__, __FUNCTION__, \
104 #define OVS_DB_POLL_TIMEOUT 1 /* poll receive timeout (sec) */
105 #define OVS_DB_POLL_READ_BLOCK_SIZE 512 /* read block size (bytes) */
106 #define OVS_DB_DEFAULT_DB_NAME "Open_vSwitch"
108 #define OVS_DB_EVENT_NONE 0
109 #define OVS_DB_EVENT_TIMEOUT 5 /* event thread timeout (sec) */
110 #define OVS_DB_EVENT_TERMINATE 1
111 #define OVS_DB_EVENT_CONN_ESTABLISHED 2
112 #define OVS_DB_EVENT_CONN_TERMINATED 3
114 #define OVS_DB_POLL_STATE_RUNNING 1
115 #define OVS_DB_POLL_STATE_EXITING 2
117 #define OVS_DB_SEND_REQ_TIMEOUT 5 /* send request timeout (sec) */
119 #define OVS_YAJL_CALL(func, ...) \
121 yajl_gen_ret = yajl_gen_status_ok; \
122 if ((yajl_gen_ret = func(__VA_ARGS__)) != yajl_gen_status_ok) \
123 goto yajl_gen_failure; \
125 #define OVS_YAJL_ERROR_BUFFER_SIZE 1024
126 #define OVS_ERROR_BUFF_SIZE 512
127 #define OVS_UID_STR_SIZE 17 /* 64-bit HEX string len + '\0' */
129 /* JSON reader internal data */
130 struct ovs_json_reader_s {
136 typedef struct ovs_json_reader_s ovs_json_reader_t;
138 /* Result callback declaration */
139 struct ovs_result_cb_s {
141 ovs_db_result_cb_t call;
143 typedef struct ovs_result_cb_s ovs_result_cb_t;
145 /* Table callback declaration */
146 struct ovs_table_cb_s {
147 ovs_db_table_cb_t call;
149 typedef struct ovs_table_cb_s ovs_table_cb_t;
151 /* Callback declaration */
152 struct ovs_callback_s {
155 ovs_result_cb_t result;
156 ovs_table_cb_t table;
158 struct ovs_callback_s *next;
159 struct ovs_callback_s *prev;
161 typedef struct ovs_callback_s ovs_callback_t;
163 /* Event thread data declaration */
164 struct ovs_event_thread_s {
166 pthread_mutex_t mutex;
170 typedef struct ovs_event_thread_s ovs_event_thread_t;
172 /* Poll thread data declaration */
173 struct ovs_poll_thread_s {
175 pthread_mutex_t mutex;
178 typedef struct ovs_poll_thread_s ovs_poll_thread_t;
180 /* OVS DB internal data declaration */
182 ovs_poll_thread_t poll_thread;
183 ovs_event_thread_t event_thread;
184 pthread_mutex_t mutex;
185 ovs_callback_t *remote_cb;
186 ovs_db_callback_t cb;
187 char service[OVS_DB_ADDR_SERVICE_SIZE];
188 char node[OVS_DB_ADDR_NODE_SIZE];
189 char unix_path[OVS_DB_ADDR_NODE_SIZE];
193 /* Global variables */
194 static uint64_t ovs_uid = 0;
195 static pthread_mutex_t ovs_uid_mutex = PTHREAD_MUTEX_INITIALIZER;
197 /* Post an event to event thread.
198 * Possible events are:
199 * OVS_DB_EVENT_TERMINATE
200 * OVS_DB_EVENT_CONN_ESTABLISHED
201 * OVS_DB_EVENT_CONN_TERMINATED
203 static void ovs_db_event_post(ovs_db_t *pdb, int event) {
204 pthread_mutex_lock(&pdb->event_thread.mutex);
205 pdb->event_thread.value = event;
206 pthread_mutex_unlock(&pdb->event_thread.mutex);
207 pthread_cond_signal(&pdb->event_thread.cond);
210 /* Check if POLL thread is still running. Returns
211 * 1 if running otherwise 0 is returned */
212 static _Bool ovs_db_poll_is_running(ovs_db_t *pdb) {
214 pthread_mutex_lock(&pdb->poll_thread.mutex);
215 state = pdb->poll_thread.state;
216 pthread_mutex_unlock(&pdb->poll_thread.mutex);
217 return state == OVS_DB_POLL_STATE_RUNNING;
220 /* Generate unique identifier (UID). It is used by OVS DB API
221 * to set "id" field for any OVS DB JSON request. */
222 static uint64_t ovs_uid_generate() {
224 pthread_mutex_lock(&ovs_uid_mutex);
226 pthread_mutex_unlock(&ovs_uid_mutex);
231 * Callback API. These function are used to store
232 * registered callbacks in OVS DB API.
235 /* Add new callback into OVS DB object */
236 static void ovs_db_callback_add(ovs_db_t *pdb, ovs_callback_t *new_cb) {
237 pthread_mutex_lock(&pdb->mutex);
239 pdb->remote_cb->prev = new_cb;
240 new_cb->next = pdb->remote_cb;
242 pdb->remote_cb = new_cb;
243 pthread_mutex_unlock(&pdb->mutex);
246 /* Remove callback from OVS DB object */
247 static void ovs_db_callback_remove(ovs_db_t *pdb, ovs_callback_t *del_cb) {
248 pthread_mutex_lock(&pdb->mutex);
249 ovs_callback_t *pre_cb = del_cb->prev;
250 ovs_callback_t *next_cb = del_cb->next;
253 next_cb->prev = del_cb->prev;
256 pre_cb->next = del_cb->next;
258 pdb->remote_cb = del_cb->next;
261 pthread_mutex_unlock(&pdb->mutex);
264 /* Remove all callbacks form OVS DB object */
265 static void ovs_db_callback_remove_all(ovs_db_t *pdb) {
266 pthread_mutex_lock(&pdb->mutex);
267 while (pdb->remote_cb != NULL) {
268 ovs_callback_t *del_cb = pdb->remote_cb;
269 pdb->remote_cb = del_cb->next;
272 pthread_mutex_unlock(&pdb->mutex);
275 /* Get/find callback in OVS DB object by UID. Returns pointer
276 * to requested callback otherwise NULL is returned.
279 * The OVS DB mutex MUST be locked by the caller
280 * to make sure that returned callback is still valid.
282 static ovs_callback_t *ovs_db_callback_get(ovs_db_t *pdb, uint64_t uid) {
283 for (ovs_callback_t *cb = pdb->remote_cb; cb != NULL; cb = cb->next)
289 /* Send all requested data to the socket. Returns 0 if
290 * ALL request data has been sent otherwise negative value
292 static int ovs_db_data_send(const ovs_db_t *pdb, const char *data, size_t len) {
298 if ((nbytes = send(pdb->sock, data + off, rem, 0)) <= 0)
300 rem -= (size_t)nbytes;
301 off += (size_t)nbytes;
307 * YAJL (Yet Another JSON Library) helper functions
308 * Documentation (https://lloyd.github.io/yajl/)
311 /* Add null-terminated string into YAJL generator handle (JSON object).
312 * Similar function to yajl_gen_string() but takes null-terminated string
313 * instead of string and its length.
315 * jgen - YAJL generator handle allocated by yajl_gen_alloc()
316 * string - Null-terminated string
318 static yajl_gen_status ovs_yajl_gen_tstring(yajl_gen hander,
319 const char *string) {
320 return yajl_gen_string(hander, (const unsigned char *)string, strlen(string));
323 /* Add YAJL value into YAJL generator handle (JSON object)
325 * jgen - YAJL generator handle allocated by yajl_gen_alloc()
326 * jval - YAJL value usually returned by yajl_tree_get()
328 static yajl_gen_status ovs_yajl_gen_val(yajl_gen jgen, yajl_val jval) {
329 size_t array_len = 0;
330 yajl_val *jvalues = NULL;
331 yajl_val jobj_value = NULL;
332 const char *obj_key = NULL;
334 yajl_gen_status yajl_gen_ret = yajl_gen_status_ok;
337 return yajl_gen_generation_complete;
339 if (YAJL_IS_STRING(jval))
340 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, YAJL_GET_STRING(jval));
341 else if (YAJL_IS_DOUBLE(jval))
342 OVS_YAJL_CALL(yajl_gen_double, jgen, YAJL_GET_DOUBLE(jval));
343 else if (YAJL_IS_INTEGER(jval))
344 OVS_YAJL_CALL(yajl_gen_double, jgen, YAJL_GET_INTEGER(jval));
345 else if (YAJL_IS_TRUE(jval))
346 OVS_YAJL_CALL(yajl_gen_bool, jgen, 1);
347 else if (YAJL_IS_FALSE(jval))
348 OVS_YAJL_CALL(yajl_gen_bool, jgen, 0);
349 else if (YAJL_IS_NULL(jval))
350 OVS_YAJL_CALL(yajl_gen_null, jgen);
351 else if (YAJL_IS_ARRAY(jval)) {
352 /* create new array and add all elements into the array */
353 array_len = YAJL_GET_ARRAY(jval)->len;
354 jvalues = YAJL_GET_ARRAY(jval)->values;
355 OVS_YAJL_CALL(yajl_gen_array_open, jgen);
356 for (size_t i = 0; i < array_len; i++)
357 OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jvalues[i]);
358 OVS_YAJL_CALL(yajl_gen_array_close, jgen);
359 } else if (YAJL_IS_OBJECT(jval)) {
360 /* create new object and add all elements into the object */
361 OVS_YAJL_CALL(yajl_gen_map_open, jgen);
362 obj_len = YAJL_GET_OBJECT(jval)->len;
363 for (size_t i = 0; i < obj_len; i++) {
364 obj_key = YAJL_GET_OBJECT(jval)->keys[i];
365 jobj_value = YAJL_GET_OBJECT(jval)->values[i];
366 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, obj_key);
367 OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jobj_value);
369 OVS_YAJL_CALL(yajl_gen_map_close, jgen);
371 OVS_ERROR("%s() unsupported value type %d (skip)", __FUNCTION__,
373 goto yajl_gen_failure;
375 return yajl_gen_status_ok;
378 OVS_ERROR("%s() error to generate value", __FUNCTION__);
382 /* OVS DB echo request handler. When OVS DB sends
383 * "echo" request to the client, client should generate
384 * "echo" replay with the same content received in the
386 static int ovs_db_table_echo_cb(const ovs_db_t *pdb, yajl_val jnode) {
391 const char *resp = NULL;
392 const char *params_path[] = {"params", NULL};
393 const char *id_path[] = {"id", NULL};
394 yajl_gen_status yajl_gen_ret;
396 if ((jgen = yajl_gen_alloc(NULL)) == NULL)
399 /* check & get request attributes */
400 if ((jparams = yajl_tree_get(jnode, params_path, yajl_t_array)) == NULL ||
401 ((jid = yajl_tree_get(jnode, id_path, yajl_t_any)) == NULL)) {
402 OVS_ERROR("parse echo request failed");
403 goto yajl_gen_failure;
406 /* generate JSON echo response */
407 OVS_YAJL_CALL(yajl_gen_map_open, jgen);
409 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "result");
410 OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jparams);
412 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "error");
413 OVS_YAJL_CALL(yajl_gen_null, jgen);
415 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "id");
416 OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jid);
418 OVS_YAJL_CALL(yajl_gen_map_close, jgen);
419 OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)&resp,
422 /* send the response */
423 OVS_DEBUG("response: %s", resp);
424 if (ovs_db_data_send(pdb, resp, resp_len) < 0) {
425 OVS_ERROR("send echo reply failed");
426 goto yajl_gen_failure;
428 /* clean up and return success */
429 yajl_gen_clear(jgen);
434 yajl_gen_clear(jgen);
438 /* Get OVS DB registered callback by YAJL val. The YAJL
439 * value should be YAJL string (UID). Returns NULL if
440 * callback hasn't been found. See also ovs_db_callback_get()
441 * description for addition info.
443 static ovs_callback_t *ovs_db_table_callback_get(ovs_db_t *pdb, yajl_val jid) {
445 const char *suid = NULL;
448 if (jid && YAJL_IS_STRING(jid)) {
449 suid = YAJL_GET_STRING(jid);
450 uid = (uint64_t)strtoul(suid, &endptr, 16);
451 if (*endptr == '\0' && uid)
452 return ovs_db_callback_get(pdb, uid);
458 /* OVS DB table update event handler.
459 * This callback is called by POLL thread if OVS DB
460 * table update callback is received from the DB
461 * server. Once registered callback found, it's called
462 * by this handler. */
463 static int ovs_db_table_update_cb(ovs_db_t *pdb, yajl_val jnode) {
464 ovs_callback_t *cb = NULL;
467 yajl_val jtable_updates;
468 const char *params_path[] = {"params", NULL};
469 const char *id_path[] = {"id", NULL};
471 /* check & get request attributes */
472 if ((jparams = yajl_tree_get(jnode, params_path, yajl_t_array)) == NULL ||
473 (yajl_tree_get(jnode, id_path, yajl_t_null) == NULL)) {
474 OVS_ERROR("invalid OVS DB request received");
478 /* check array length: [<json-value>, <table-updates>] */
479 if ((YAJL_GET_ARRAY(jparams) == NULL) ||
480 (YAJL_GET_ARRAY(jparams)->len != 2)) {
481 OVS_ERROR("invalid OVS DB request received");
485 jvalue = YAJL_GET_ARRAY(jparams)->values[0];
486 jtable_updates = YAJL_GET_ARRAY(jparams)->values[1];
487 if ((!YAJL_IS_OBJECT(jtable_updates)) || (!YAJL_IS_STRING(jvalue))) {
488 OVS_ERROR("invalid OVS DB request id or table update received");
492 /* find registered callback based on <json-value> */
493 pthread_mutex_lock(&pdb->mutex);
494 cb = ovs_db_table_callback_get(pdb, jvalue);
495 if (cb == NULL || cb->table.call == NULL) {
496 OVS_ERROR("No OVS DB table update callback found");
497 pthread_mutex_unlock(&pdb->mutex);
501 /* call registered callback */
502 cb->table.call(jtable_updates);
503 pthread_mutex_unlock(&pdb->mutex);
507 /* OVS DB result request handler.
508 * This callback is called by POLL thread if OVS DB
509 * result reply is received from the DB server.
510 * Once registered callback found, it's called
511 * by this handler. */
512 static int ovs_db_result_cb(ovs_db_t *pdb, yajl_val jnode) {
513 ovs_callback_t *cb = NULL;
517 const char *result_path[] = {"result", NULL};
518 const char *error_path[] = {"error", NULL};
519 const char *id_path[] = {"id", NULL};
521 jresult = yajl_tree_get(jnode, result_path, yajl_t_any);
522 jerror = yajl_tree_get(jnode, error_path, yajl_t_any);
523 jid = yajl_tree_get(jnode, id_path, yajl_t_string);
525 /* check & get result attributes */
526 if (!jresult || !jerror || !jid)
529 /* try to find registered callback */
530 pthread_mutex_lock(&pdb->mutex);
531 cb = ovs_db_table_callback_get(pdb, jid);
532 if (cb != NULL && cb->result.call != NULL) {
533 /* call registered callback */
534 cb->result.call(jresult, jerror);
535 /* unlock owner of the reply */
536 sem_post(&cb->result.sync);
539 pthread_mutex_unlock(&pdb->mutex);
543 /* Handle JSON data (one request) and call
544 * appropriate event OVS DB handler. Currently,
545 * update callback 'ovs_db_table_update_cb' and
546 * result callback 'ovs_db_result_cb' is supported.
548 static int ovs_db_json_data_process(ovs_db_t *pdb, const char *data,
550 const char *method = NULL;
551 char yajl_errbuf[OVS_YAJL_ERROR_BUFFER_SIZE];
552 const char *method_path[] = {"method", NULL};
553 const char *result_path[] = {"result", NULL};
555 yajl_val jnode, jval;
557 /* duplicate the data to make null-terminated string
558 * required for yajl_tree_parse() */
559 if ((sjson = calloc(1, len + 1)) == NULL)
562 sstrncpy(sjson, data, len + 1);
563 OVS_DEBUG("[len=%zu] %s", len, sjson);
565 /* parse json data */
566 jnode = yajl_tree_parse(sjson, yajl_errbuf, sizeof(yajl_errbuf));
568 OVS_ERROR("yajl_tree_parse() %s", yajl_errbuf);
573 /* get method name */
574 if ((jval = yajl_tree_get(jnode, method_path, yajl_t_string)) != NULL) {
575 if ((method = YAJL_GET_STRING(jval)) == NULL) {
576 yajl_tree_free(jnode);
580 if (strcmp("echo", method) == 0) {
581 /* echo request from the server */
582 if (ovs_db_table_echo_cb(pdb, jnode) < 0)
583 OVS_ERROR("handle echo request failed");
584 } else if (strcmp("update", method) == 0) {
585 /* update notification */
586 if (ovs_db_table_update_cb(pdb, jnode) < 0)
587 OVS_ERROR("handle update notification failed");
589 } else if ((jval = yajl_tree_get(jnode, result_path, yajl_t_any)) != NULL) {
590 /* result notification */
591 if (ovs_db_result_cb(pdb, jnode) < 0)
592 OVS_ERROR("handle result reply failed");
594 OVS_ERROR("connot find method or result failed");
597 yajl_tree_free(jnode);
603 * JSON reader implementation.
605 * This module process raw JSON data (byte stream) and
606 * returns fully-fledged JSON data which can be processed
607 * (parsed) by YAJL later.
610 /* Allocate JSON reader instance */
611 static ovs_json_reader_t *ovs_json_reader_alloc() {
612 ovs_json_reader_t *jreader = NULL;
614 if ((jreader = calloc(sizeof(ovs_json_reader_t), 1)) == NULL)
620 /* Push raw data into into the JSON reader for processing */
621 static int ovs_json_reader_push_data(ovs_json_reader_t *jreader,
622 const char *data, size_t data_len) {
623 char *new_buff = NULL;
624 size_t available = jreader->buff_size - jreader->buff_offset;
626 /* check/update required memory space */
627 if (available < data_len) {
628 OVS_DEBUG("Reallocate buffer [size=%d, available=%d required=%d]",
629 (int)jreader->buff_size, (int)available, (int)data_len);
631 /* allocate new chunk of memory */
632 new_buff = realloc(jreader->buff_ptr, (jreader->buff_size + data_len));
633 if (new_buff == NULL)
636 /* point to new allocated memory */
637 jreader->buff_ptr = new_buff;
638 jreader->buff_size += data_len;
641 /* store input data */
642 memcpy(jreader->buff_ptr + jreader->buff_offset, data, data_len);
643 jreader->buff_offset += data_len;
647 /* Pop one fully-fledged JSON if already exists. Returns 0 if
648 * completed JSON already exists otherwise negative value is
650 static int ovs_json_reader_pop(ovs_json_reader_t *jreader,
651 const char **json_ptr, size_t *json_len_ptr) {
656 /* search open/close brace */
657 for (size_t i = jreader->json_offset; i < jreader->buff_offset; i++) {
658 if (jreader->buff_ptr[i] == '{') {
660 } else if (jreader->buff_ptr[i] == '}')
664 *json_ptr = jreader->buff_ptr + jreader->json_offset;
665 *json_len_ptr = json_len + 1;
666 jreader->json_offset = i + 1;
670 /* increase JSON data length */
675 if (jreader->json_offset) {
676 if (jreader->json_offset < jreader->buff_offset) {
677 /* shift data to the beginning of the buffer
678 * and zero rest of the buffer data */
679 json = &jreader->buff_ptr[jreader->json_offset];
680 json_len = jreader->buff_offset - jreader->json_offset;
681 for (size_t i = 0; i < jreader->buff_size; i++)
682 jreader->buff_ptr[i] = ((i < json_len) ? (json[i]) : (0));
683 jreader->buff_offset = json_len;
685 /* reset the buffer */
686 jreader->buff_offset = 0;
688 /* data is at the beginning of the buffer */
689 jreader->json_offset = 0;
695 /* Reset JSON reader. It is useful when start processing
696 * new raw data. E.g.: in case of lost stream connection.
698 static void ovs_json_reader_reset(ovs_json_reader_t *jreader) {
700 jreader->buff_offset = 0;
701 jreader->json_offset = 0;
705 /* Release internal data allocated for JSON reader */
706 static void ovs_json_reader_free(ovs_json_reader_t *jreader) {
708 free(jreader->buff_ptr);
713 /* Reconnect to OVS DB and call the OVS DB post connection init callback
714 * if connection has been established.
716 static void ovs_db_reconnect(ovs_db_t *pdb) {
717 const char *node_info = pdb->node;
718 struct addrinfo *result;
720 if (pdb->unix_path[0] != '\0') {
721 /* use UNIX socket instead of INET address */
722 node_info = pdb->unix_path;
723 result = calloc(1, sizeof(struct addrinfo));
724 struct sockaddr_un *sa_unix = calloc(1, sizeof(struct sockaddr_un));
725 if (result == NULL || sa_unix == NULL) {
730 result->ai_family = AF_UNIX;
731 result->ai_socktype = SOCK_STREAM;
732 result->ai_addrlen = sizeof(*sa_unix);
733 result->ai_addr = (struct sockaddr *)sa_unix;
734 sa_unix->sun_family = result->ai_family;
735 sstrncpy(sa_unix->sun_path, pdb->unix_path, sizeof(sa_unix->sun_path));
737 /* inet socket address */
738 struct addrinfo hints;
740 /* setup criteria for selecting the socket address */
741 memset(&hints, 0, sizeof(hints));
742 hints.ai_family = AF_UNSPEC;
743 hints.ai_socktype = SOCK_STREAM;
745 /* get socket addresses */
746 int ret = getaddrinfo(pdb->node, pdb->service, &hints, &result);
748 OVS_ERROR("getaddrinfo(): %s", gai_strerror(ret));
752 /* try to connect to the server */
753 for (struct addrinfo *rp = result; rp != NULL; rp = rp->ai_next) {
754 char errbuff[OVS_ERROR_BUFF_SIZE];
755 int sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
757 sstrerror(errno, errbuff, sizeof(errbuff));
758 OVS_DEBUG("socket(): %s", errbuff);
761 if (connect(sock, rp->ai_addr, rp->ai_addrlen) < 0) {
763 sstrerror(errno, errbuff, sizeof(errbuff));
764 OVS_DEBUG("connect(): %s [family=%d]", errbuff, rp->ai_family);
766 /* send notification to event thread */
768 ovs_db_event_post(pdb, OVS_DB_EVENT_CONN_ESTABLISHED);
774 OVS_ERROR("connect to \"%s\" failed", node_info);
776 freeaddrinfo(result);
779 /* POLL worker thread.
780 * It listens on OVS DB connection for incoming
781 * requests/reply/events etc. Also, it reconnects to OVS DB
782 * if connection has been lost.
784 static void *ovs_poll_worker(void *arg) {
785 ovs_db_t *pdb = (ovs_db_t *)arg; /* pointer to OVS DB */
786 ovs_json_reader_t *jreader = NULL;
787 struct pollfd poll_fd = {
788 .fd = pdb->sock, .events = POLLIN | POLLPRI, .revents = 0,
791 /* create JSON reader instance */
792 if ((jreader = ovs_json_reader_alloc()) == NULL) {
793 OVS_ERROR("initialize json reader failed");
798 while (ovs_db_poll_is_running(pdb)) {
799 char errbuff[OVS_ERROR_BUFF_SIZE];
800 poll_fd.fd = pdb->sock;
801 int poll_ret = poll(&poll_fd, 1, /* ms */ OVS_DB_POLL_TIMEOUT * 1000);
803 sstrerror(errno, errbuff, sizeof(errbuff));
804 OVS_ERROR("poll(): %s", errbuff);
806 } else if (poll_ret == 0) {
807 OVS_DEBUG("poll(): timeout");
809 /* invalid fd, so try to reconnect */
810 ovs_db_reconnect(pdb);
813 if (poll_fd.revents & POLLNVAL) {
814 /* invalid file descriptor, clean-up */
815 ovs_db_callback_remove_all(pdb);
816 ovs_json_reader_reset(jreader);
817 /* setting poll FD to -1 tells poll() call to ignore this FD.
818 * In that case poll() call will return timeout all the time */
820 } else if ((poll_fd.revents & POLLERR) || (poll_fd.revents & POLLHUP)) {
821 /* connection is broken */
823 ovs_db_event_post(pdb, OVS_DB_EVENT_CONN_TERMINATED);
824 OVS_ERROR("poll() peer closed its end of the channel");
825 } else if ((poll_fd.revents & POLLIN) || (poll_fd.revents & POLLPRI)) {
826 /* read incoming data */
827 char buff[OVS_DB_POLL_READ_BLOCK_SIZE];
828 ssize_t nbytes = recv(poll_fd.fd, buff, sizeof(buff), 0);
830 sstrerror(errno, errbuff, sizeof(errbuff));
831 OVS_ERROR("recv(): %s", errbuff);
832 /* read error? Try to reconnect */
835 } else if (nbytes == 0) {
837 ovs_db_event_post(pdb, OVS_DB_EVENT_CONN_TERMINATED);
838 OVS_ERROR("recv() peer has performed an orderly shutdown");
841 /* read incoming data */
843 const char *json = NULL;
844 OVS_DEBUG("recv(): received %zd bytes of data", nbytes);
845 ovs_json_reader_push_data(jreader, buff, nbytes);
846 while (!ovs_json_reader_pop(jreader, &json, &json_len))
847 /* process JSON data */
848 ovs_db_json_data_process(pdb, json, json_len);
852 OVS_DEBUG("poll thread has been completed");
853 ovs_json_reader_free(jreader);
857 /* EVENT worker thread.
858 * Perform task based on incoming events. This
859 * task can be done asynchronously which allows to
860 * handle OVS DB callback like 'init_cb'.
862 static void *ovs_event_worker(void *arg) {
863 ovs_db_t *pdb = (ovs_db_t *)arg;
865 while (pdb->event_thread.value != OVS_DB_EVENT_TERMINATE) {
866 /* wait for an event */
868 clock_gettime(CLOCK_REALTIME, &ts);
869 ts.tv_sec += (OVS_DB_EVENT_TIMEOUT);
870 int ret = pthread_cond_timedwait(&pdb->event_thread.cond,
871 &pdb->event_thread.mutex, &ts);
872 if (!ret || ret == ETIMEDOUT) {
873 /* handle the event */
874 OVS_DEBUG("handle event %d", pdb->event_thread.value);
875 switch (pdb->event_thread.value) {
876 case OVS_DB_EVENT_CONN_ESTABLISHED:
877 if (pdb->cb.post_conn_init)
878 pdb->cb.post_conn_init(pdb);
880 pdb->event_thread.value = OVS_DB_EVENT_NONE;
882 case OVS_DB_EVENT_CONN_TERMINATED:
883 if (pdb->cb.post_conn_terminate)
884 pdb->cb.post_conn_terminate();
886 pdb->event_thread.value = OVS_DB_EVENT_NONE;
888 case OVS_DB_EVENT_NONE:
890 OVS_DEBUG("no event received (timeout)");
893 OVS_DEBUG("unknown event received");
897 /* unexpected error */
898 OVS_ERROR("pthread_cond_timedwait() failed");
903 OVS_DEBUG("event thread has been completed");
907 /* Initialize EVENT thread */
908 static int ovs_db_event_thread_init(ovs_db_t *pdb) {
909 pdb->event_thread.tid = (pthread_t){0};
910 /* init event thread condition variable */
911 if (pthread_cond_init(&pdb->event_thread.cond, NULL)) {
914 /* init event thread mutex */
915 if (pthread_mutex_init(&pdb->event_thread.mutex, NULL)) {
916 pthread_cond_destroy(&pdb->event_thread.cond);
919 /* Hold the event thread mutex. It ensures that no events
920 * will be lost while thread is still starting. Once event
921 * thread is started and ready to accept events, it will release
923 if (pthread_mutex_lock(&pdb->event_thread.mutex)) {
924 pthread_mutex_destroy(&pdb->event_thread.mutex);
925 pthread_cond_destroy(&pdb->event_thread.cond);
928 /* start event thread */
930 if (plugin_thread_create(&tid, NULL, ovs_event_worker, pdb,
931 "utils_ovs:event") != 0) {
932 pthread_mutex_unlock(&pdb->event_thread.mutex);
933 pthread_mutex_destroy(&pdb->event_thread.mutex);
934 pthread_cond_destroy(&pdb->event_thread.cond);
937 pdb->event_thread.tid = tid;
941 /* Terminate EVENT thread */
942 static int ovs_db_event_thread_terminate(ovs_db_t *pdb) {
943 if (pthread_equal(pdb->event_thread.tid, (pthread_t){0})) {
944 /* already terminated */
947 ovs_db_event_post(pdb, OVS_DB_EVENT_TERMINATE);
948 if (pthread_join(pdb->event_thread.tid, NULL) != 0)
950 /* Event thread always holds the thread mutex when
951 * performs some task (handles event) and releases it when
952 * while sleeping. Thus, if event thread exits, the mutex
954 pdb->event_thread.tid = (pthread_t){0};
955 pthread_mutex_unlock(&pdb->event_thread.mutex);
959 /* Destroy EVENT thread private data */
960 static void ovs_db_event_thread_data_destroy(ovs_db_t *pdb) {
962 pthread_mutex_destroy(&pdb->event_thread.mutex);
963 pthread_cond_destroy(&pdb->event_thread.cond);
966 /* Initialize POLL thread */
967 static int ovs_db_poll_thread_init(ovs_db_t *pdb) {
968 pdb->poll_thread.tid = (pthread_t){0};
969 /* init event thread mutex */
970 if (pthread_mutex_init(&pdb->poll_thread.mutex, NULL)) {
973 /* start poll thread */
975 pdb->poll_thread.state = OVS_DB_POLL_STATE_RUNNING;
976 if (plugin_thread_create(&tid, NULL, ovs_poll_worker, pdb,
977 "utils_ovs:poll") != 0) {
978 pthread_mutex_destroy(&pdb->poll_thread.mutex);
981 pdb->poll_thread.tid = tid;
985 /* Destroy POLL thread */
986 /* XXX: Must hold pdb->mutex when calling! */
987 static int ovs_db_poll_thread_destroy(ovs_db_t *pdb) {
988 if (pthread_equal(pdb->poll_thread.tid, (pthread_t){0})) {
989 /* already destroyed */
992 /* change thread state */
993 pthread_mutex_lock(&pdb->poll_thread.mutex);
994 pdb->poll_thread.state = OVS_DB_POLL_STATE_EXITING;
995 pthread_mutex_unlock(&pdb->poll_thread.mutex);
996 /* join the thread */
997 if (pthread_join(pdb->poll_thread.tid, NULL) != 0)
999 pthread_mutex_destroy(&pdb->poll_thread.mutex);
1000 pdb->poll_thread.tid = (pthread_t){0};
1005 * Public OVS DB API implementation
1008 ovs_db_t *ovs_db_init(const char *node, const char *service,
1009 const char *unix_path, ovs_db_callback_t *cb) {
1011 if (node == NULL || service == NULL || unix_path == NULL)
1014 /* allocate db data & fill it */
1015 ovs_db_t *pdb = calloc(1, sizeof(*pdb));
1020 /* store the OVS DB address */
1021 sstrncpy(pdb->node, node, sizeof(pdb->node));
1022 sstrncpy(pdb->service, service, sizeof(pdb->service));
1023 sstrncpy(pdb->unix_path, unix_path, sizeof(pdb->unix_path));
1025 /* setup OVS DB callbacks */
1029 /* init OVS DB mutex attributes */
1030 pthread_mutexattr_t mutex_attr;
1031 if (pthread_mutexattr_init(&mutex_attr)) {
1032 OVS_ERROR("OVS DB mutex attribute init failed");
1036 /* set OVS DB mutex as recursive */
1037 if (pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE)) {
1038 OVS_ERROR("Failed to set OVS DB mutex as recursive");
1039 pthread_mutexattr_destroy(&mutex_attr);
1043 /* init OVS DB mutex */
1044 if (pthread_mutex_init(&pdb->mutex, &mutex_attr)) {
1045 OVS_ERROR("OVS DB mutex init failed");
1046 pthread_mutexattr_destroy(&mutex_attr);
1050 /* destroy mutex attributes */
1051 pthread_mutexattr_destroy(&mutex_attr);
1053 /* init event thread */
1054 if (ovs_db_event_thread_init(pdb) < 0) {
1055 ovs_db_destroy(pdb);
1059 /* init polling thread */
1060 if (ovs_db_poll_thread_init(pdb) < 0) {
1061 ovs_db_destroy(pdb);
1067 int ovs_db_send_request(ovs_db_t *pdb, const char *method, const char *params,
1068 ovs_db_result_cb_t cb) {
1070 yajl_gen_status yajl_gen_ret;
1073 ovs_callback_t *new_cb = NULL;
1075 char uid_buff[OVS_UID_STR_SIZE];
1076 const char *req = NULL;
1081 if (!pdb || !method || !params)
1084 if ((jgen = yajl_gen_alloc(NULL)) == NULL)
1087 /* try to parse params */
1088 if ((jparams = yajl_tree_parse(params, NULL, 0)) == NULL) {
1089 OVS_ERROR("params is not a JSON string");
1090 yajl_gen_clear(jgen);
1094 /* generate method field */
1095 OVS_YAJL_CALL(yajl_gen_map_open, jgen);
1097 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "method");
1098 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, method);
1100 /* generate params field */
1101 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "params");
1102 OVS_YAJL_CALL(ovs_yajl_gen_val, jgen, jparams);
1103 yajl_tree_free(jparams);
1105 /* generate id field */
1106 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "id");
1107 uid = ovs_uid_generate();
1108 snprintf(uid_buff, sizeof(uid_buff), "%" PRIX64, uid);
1109 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, uid_buff);
1111 OVS_YAJL_CALL(yajl_gen_map_close, jgen);
1114 /* register result callback */
1115 if ((new_cb = calloc(1, sizeof(ovs_callback_t))) == NULL)
1116 goto yajl_gen_failure;
1118 /* add new callback to front */
1119 sem_init(&new_cb->result.sync, 0, 0);
1120 new_cb->result.call = cb;
1122 ovs_db_callback_add(pdb, new_cb);
1125 /* send the request */
1126 OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)&req, &req_len);
1127 OVS_DEBUG("%s", req);
1128 if (!ovs_db_data_send(pdb, req, req_len)) {
1130 /* wait for result */
1131 clock_gettime(CLOCK_REALTIME, &ts);
1132 ts.tv_sec += OVS_DB_SEND_REQ_TIMEOUT;
1133 if (sem_timedwait(&new_cb->result.sync, &ts) < 0) {
1134 OVS_ERROR("%s() no replay received within %d sec", __FUNCTION__,
1135 OVS_DB_SEND_REQ_TIMEOUT);
1140 OVS_ERROR("ovs_db_data_send() failed");
1146 /* destroy callback */
1147 sem_destroy(&new_cb->result.sync);
1148 ovs_db_callback_remove(pdb, new_cb);
1151 /* release memory */
1152 yajl_gen_clear(jgen);
1153 return (yajl_gen_ret != yajl_gen_status_ok) ? (-1) : ret;
1156 int ovs_db_table_cb_register(ovs_db_t *pdb, const char *tb_name,
1157 const char **tb_column,
1158 ovs_db_table_cb_t update_cb,
1159 ovs_db_result_cb_t result_cb, unsigned int flags) {
1161 yajl_gen_status yajl_gen_ret;
1162 ovs_callback_t *new_cb = NULL;
1163 char uid_str[OVS_UID_STR_SIZE];
1169 if (pdb == NULL || tb_name == NULL || update_cb == NULL)
1172 /* allocate new update callback */
1173 if ((new_cb = calloc(1, sizeof(ovs_callback_t))) == NULL)
1176 /* init YAJL generator */
1177 if ((jgen = yajl_gen_alloc(NULL)) == NULL) {
1182 /* add new callback to front */
1183 new_cb->table.call = update_cb;
1184 new_cb->uid = ovs_uid_generate();
1185 ovs_db_callback_add(pdb, new_cb);
1187 /* make update notification request
1188 * [<db-name>, <json-value>, <monitor-requests>] */
1189 OVS_YAJL_CALL(yajl_gen_array_open, jgen);
1191 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, OVS_DB_DEFAULT_DB_NAME);
1193 /* uid string <json-value> */
1194 snprintf(uid_str, sizeof(uid_str), "%" PRIX64, new_cb->uid);
1195 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, uid_str);
1197 /* <monitor-requests> */
1198 OVS_YAJL_CALL(yajl_gen_map_open, jgen);
1200 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, tb_name);
1201 OVS_YAJL_CALL(yajl_gen_array_open, jgen);
1203 /* <monitor-request> */
1204 OVS_YAJL_CALL(yajl_gen_map_open, jgen);
1207 /* columns within the table to be monitored */
1208 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "columns");
1209 OVS_YAJL_CALL(yajl_gen_array_open, jgen);
1210 for (; *tb_column; tb_column++)
1211 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, *tb_column);
1212 OVS_YAJL_CALL(yajl_gen_array_close, jgen);
1214 /* specify select option */
1215 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "select");
1217 OVS_YAJL_CALL(yajl_gen_map_open, jgen);
1219 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "initial");
1220 OVS_YAJL_CALL(yajl_gen_bool, jgen,
1221 flags & OVS_DB_TABLE_CB_FLAG_INITIAL);
1222 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "insert");
1223 OVS_YAJL_CALL(yajl_gen_bool, jgen,
1224 flags & OVS_DB_TABLE_CB_FLAG_INSERT);
1225 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "delete");
1226 OVS_YAJL_CALL(yajl_gen_bool, jgen,
1227 flags & OVS_DB_TABLE_CB_FLAG_DELETE);
1228 OVS_YAJL_CALL(ovs_yajl_gen_tstring, jgen, "modify");
1229 OVS_YAJL_CALL(yajl_gen_bool, jgen,
1230 flags & OVS_DB_TABLE_CB_FLAG_MODIFY);
1232 OVS_YAJL_CALL(yajl_gen_map_close, jgen);
1235 OVS_YAJL_CALL(yajl_gen_map_close, jgen);
1237 OVS_YAJL_CALL(yajl_gen_array_close, jgen);
1239 OVS_YAJL_CALL(yajl_gen_map_close, jgen);
1241 OVS_YAJL_CALL(yajl_gen_array_close, jgen);
1243 /* make a request to subscribe to given table */
1244 OVS_YAJL_CALL(yajl_gen_get_buf, jgen, (const unsigned char **)¶ms,
1246 if (ovs_db_send_request(pdb, "monitor", params, result_cb) < 0) {
1247 OVS_ERROR("Failed to subscribe to \"%s\" table", tb_name);
1252 /* release memory */
1253 yajl_gen_clear(jgen);
1257 int ovs_db_destroy(ovs_db_t *pdb) {
1265 /* stop event thread */
1266 if (ovs_db_event_thread_terminate(pdb) < 0) {
1267 OVS_ERROR("stop event thread failed");
1271 /* try to lock the structure before releasing */
1272 if ((ret = pthread_mutex_lock(&pdb->mutex))) {
1273 OVS_ERROR("pthread_mutex_lock() DB mutex lock failed (%d)", ret);
1277 /* stop poll thread and destroy thread's private data */
1278 if (ovs_db_poll_thread_destroy(pdb) < 0) {
1279 OVS_ERROR("destroy poll thread failed");
1283 /* destroy event thread private data */
1284 ovs_db_event_thread_data_destroy(pdb);
1286 pthread_mutex_unlock(&pdb->mutex);
1288 /* unsubscribe callbacks */
1289 ovs_db_callback_remove_all(pdb);
1291 /* close connection */
1295 /* release DB handler */
1296 pthread_mutex_destroy(&pdb->mutex);
1302 * Public OVS utils API implementation
1305 /* Get YAJL value by key from YAJL dictionary
1309 * "key_a" : <YAJL return value>
1310 * "key_b" : <YAJL return value>
1313 yajl_val ovs_utils_get_value_by_key(yajl_val jval, const char *key) {
1314 const char *obj_key = NULL;
1317 if (!YAJL_IS_OBJECT(jval) || (key == NULL))
1320 /* find a value by key */
1321 for (size_t i = 0; i < YAJL_GET_OBJECT(jval)->len; i++) {
1322 obj_key = YAJL_GET_OBJECT(jval)->keys[i];
1323 if (strcmp(obj_key, key) == 0)
1324 return YAJL_GET_OBJECT(jval)->values[i];
1330 /* Get OVS DB map value by given map key
1335 * A 2-element JSON array that represents a pair within a database
1336 * map. The first element is an <atom> that represents the key, and
1337 * the second element is an <atom> that represents the value.
1340 * A 2-element JSON array that represents a database map value. The
1341 * first element of the array must be the string "map", and the
1342 * second element must be an array of zero or more <pair>s giving the
1343 * values in the map. All of the <pair>s must have the same key and
1349 * [ "key_a", <YAJL value>], [ "key_b", <YAJL value>], ...
1353 yajl_val ovs_utils_get_map_value(yajl_val jval, const char *key) {
1355 size_t array_len = 0;
1356 yajl_val *map_values = NULL;
1357 yajl_val *array_values = NULL;
1358 const char *str_val = NULL;
1360 /* check YAJL array */
1361 if (!YAJL_IS_ARRAY(jval) || (key == NULL))
1364 /* check a database map value (2-element, first one should be a string */
1365 array_len = YAJL_GET_ARRAY(jval)->len;
1366 array_values = YAJL_GET_ARRAY(jval)->values;
1367 if ((array_len != 2) || (!YAJL_IS_STRING(array_values[0])) ||
1368 (!YAJL_IS_ARRAY(array_values[1])))
1371 /* check first element of the array */
1372 str_val = YAJL_GET_STRING(array_values[0]);
1373 if (strcmp("map", str_val) != 0)
1376 /* try to find map value by map key */
1377 map_len = YAJL_GET_ARRAY(array_values[1])->len;
1378 map_values = YAJL_GET_ARRAY(array_values[1])->values;
1379 for (size_t i = 0; i < map_len; i++) {
1380 /* check YAJL array */
1381 if (!YAJL_IS_ARRAY(map_values[i]))
1384 /* check a database pair value (2-element, first one represents a key
1385 * and it should be a string in our case */
1386 array_len = YAJL_GET_ARRAY(map_values[i])->len;
1387 array_values = YAJL_GET_ARRAY(map_values[i])->values;
1388 if ((array_len != 2) || (!YAJL_IS_STRING(array_values[0])))
1391 /* return map value if given key equals map key */
1392 str_val = YAJL_GET_STRING(array_values[0]);
1393 if (strcmp(key, str_val) == 0)
1394 return array_values[1];