542df9d414b6cb664d00266a22c2ff82b72c2443
[vpp.git] / src / vpp-api / client / client.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <assert.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <stddef.h>
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/mman.h>
22 #include <sys/stat.h>
23 #include <netinet/in.h>
24 #include <netdb.h>
25 #include <signal.h>
26 #include <stdbool.h>
27 #include <vnet/vnet.h>
28 #include <vlib/vlib.h>
29 #include <vlib/unix/unix.h>
30 #include <vlibapi/api.h>
31 #include <vlibmemory/api.h>
32
33 #include <vlibmemory/memclnt.api_enum.h>
34 #include <vlibmemory/memclnt.api_types.h>
35
36 #include "vppapiclient.h"
37
38 bool timeout_cancelled;
39 bool timeout_in_progress;
40 bool rx_thread_done;
41
42 /*
43  * Asynchronous mode:
44  *  Client registers a callback. All messages are sent to the callback.
45  * Synchronous mode:
46  *  Client calls blocking read().
47  *  Clients are expected to collate events on a queue.
48  *  vac_write() -> suspends RX thread
49  *  vac_read() -> resumes RX thread
50  */
51
52 typedef struct {
53   u8 connected_to_vlib;
54   pthread_t rx_thread_handle;
55   pthread_t timeout_thread_handle;
56   pthread_mutex_t queue_lock;
57   pthread_cond_t suspend_cv;
58   pthread_cond_t resume_cv;
59   pthread_mutex_t timeout_lock;
60   u8 timeout_loop;
61   pthread_cond_t timeout_cv;
62   pthread_cond_t timeout_cancel_cv;
63   pthread_cond_t terminate_cv;
64 } vac_main_t;
65
66 vac_main_t vac_main;
67 vac_callback_t vac_callback;
68 u16 read_timeout = 0;
69 bool rx_is_running = false;
70 bool timeout_thread_cancelled = false;
71
72 /* Only ever allocate one heap */
73 bool mem_initialized = false;
74
75 static void
76 init (void)
77 {
78   vac_main_t *pm = &vac_main;
79   clib_memset(pm, 0, sizeof(*pm));
80   pthread_mutex_init(&pm->queue_lock, NULL);
81   pthread_cond_init(&pm->suspend_cv, NULL);
82   pthread_cond_init(&pm->resume_cv, NULL);
83   pthread_mutex_init(&pm->timeout_lock, NULL);
84   pm->timeout_loop = 1;
85   pthread_cond_init(&pm->timeout_cv, NULL);
86   pthread_cond_init(&pm->timeout_cancel_cv, NULL);
87   pthread_cond_init(&pm->terminate_cv, NULL);
88 }
89
90 static void
91 cleanup (void)
92 {
93   vac_main_t *pm = &vac_main;
94   pthread_mutex_destroy(&pm->queue_lock);
95   pthread_cond_destroy(&pm->suspend_cv);
96   pthread_cond_destroy(&pm->resume_cv);
97   pthread_mutex_destroy(&pm->timeout_lock);
98   pthread_cond_destroy(&pm->timeout_cv);
99   pthread_cond_destroy(&pm->timeout_cancel_cv);
100   pthread_cond_destroy(&pm->terminate_cv);
101   clib_memset(pm, 0, sizeof(*pm));
102 }
103
104 /*
105  * Satisfy external references when -lvlib is not available.
106  */
107 void vlib_cli_output (struct vlib_main_t * vm, char * fmt, ...)
108 {
109   clib_warning ("vlib_cli_output called...");
110 }
111
112 void
113 vac_free (void * msg)
114 {
115   vl_msg_api_free (msg);
116 }
117
118 static void
119 vac_api_handler (void *msg)
120 {
121   u16 id = ntohs(*((u16 *)msg));
122   msgbuf_t *msgbuf = (msgbuf_t *)(((u8 *)msg) - offsetof(msgbuf_t, data));
123   int l = ntohl(msgbuf->data_len);
124   if (l == 0)
125     clib_warning("Message ID %d has wrong length: %d\n", id, l);
126
127   /* Call Python callback */
128   ASSERT(vac_callback);
129   (vac_callback)(msg, l);
130   vac_free(msg);
131 }
132
133 static void *
134 vac_rx_thread_fn (void *arg)
135 {
136   svm_queue_t *q;
137   vl_api_memclnt_keepalive_t *mp;
138   vl_api_memclnt_keepalive_reply_t *rmp;
139   vac_main_t *pm = &vac_main;
140   api_main_t *am = vlibapi_get_main();
141   vl_shmem_hdr_t *shmem_hdr;
142   uword msg;
143
144   q = am->vl_input_queue;
145
146   while (1)
147     while (!svm_queue_sub(q, (u8 *)&msg, SVM_Q_WAIT, 0))
148       {
149         VL_MSG_API_UNPOISON((void *)msg);
150         u16 id = ntohs(*((u16 *)msg));
151         switch (id) {
152         case VL_API_RX_THREAD_EXIT:
153           vl_msg_api_free((void *) msg);
154           /* signal waiting threads that this thread is about to terminate */
155           pthread_mutex_lock(&pm->queue_lock);
156           rx_thread_done = true;
157           pthread_cond_signal(&pm->terminate_cv);
158           pthread_mutex_unlock(&pm->queue_lock);
159           pthread_exit(0);
160           return 0;
161           break;
162
163         case VL_API_MEMCLNT_RX_THREAD_SUSPEND:
164           vl_msg_api_free((void * )msg);
165           /* Suspend thread and signal reader */
166           pthread_mutex_lock(&pm->queue_lock);
167           pthread_cond_signal(&pm->suspend_cv);
168           /* Wait for the resume signal */
169           pthread_cond_wait (&pm->resume_cv, &pm->queue_lock);
170           pthread_mutex_unlock(&pm->queue_lock);
171           break;
172
173         case VL_API_MEMCLNT_READ_TIMEOUT:
174           clib_warning("Received read timeout in async thread\n");
175           vl_msg_api_free((void *) msg);
176           break;
177
178         case VL_API_MEMCLNT_KEEPALIVE:
179           mp = (void *)msg;
180           rmp = vl_msg_api_alloc (sizeof (*rmp));
181           clib_memset (rmp, 0, sizeof (*rmp));
182           rmp->_vl_msg_id = ntohs(VL_API_MEMCLNT_KEEPALIVE_REPLY);
183           rmp->context = mp->context;
184           shmem_hdr = am->shmem_hdr;
185           vl_msg_api_send_shmem(shmem_hdr->vl_input_queue, (u8 *)&rmp);
186           vl_msg_api_free((void *) msg);
187           break;
188
189         default:
190           vac_api_handler((void *)msg);
191         }
192       }
193 }
194
195 static void *
196 vac_timeout_thread_fn (void *arg)
197 {
198   vl_api_memclnt_read_timeout_t *ep;
199   vac_main_t *pm = &vac_main;
200   api_main_t *am = vlibapi_get_main();
201   struct timespec ts;
202   struct timeval tv;
203   int rv;
204
205   while (pm->timeout_loop)
206     {
207       /* Wait for poke */
208       pthread_mutex_lock(&pm->timeout_lock);
209       while (!timeout_in_progress)
210         pthread_cond_wait (&pm->timeout_cv, &pm->timeout_lock);
211
212       /* Starting timer */
213       gettimeofday(&tv, NULL);
214       ts.tv_sec = tv.tv_sec + read_timeout;
215       ts.tv_nsec = 0;
216
217       if (!timeout_cancelled) {
218         rv = pthread_cond_timedwait (&pm->timeout_cancel_cv,
219                                      &pm->timeout_lock, &ts);
220         if (rv == ETIMEDOUT && !timeout_thread_cancelled) {
221           ep = vl_msg_api_alloc (sizeof (*ep));
222           ep->_vl_msg_id = ntohs(VL_API_MEMCLNT_READ_TIMEOUT);
223           vl_msg_api_send_shmem(am->vl_input_queue, (u8 *)&ep);
224         }
225       }
226
227       pthread_mutex_unlock(&pm->timeout_lock);
228     }
229   pthread_exit(0);
230 }
231
232 void
233 vac_rx_suspend (void)
234 {
235   api_main_t *am = vlibapi_get_main();
236   vac_main_t *pm = &vac_main;
237   vl_api_memclnt_rx_thread_suspend_t *ep;
238
239   if (!pm->rx_thread_handle) return;
240   pthread_mutex_lock(&pm->queue_lock);
241   if (rx_is_running)
242     {
243       ep = vl_msg_api_alloc (sizeof (*ep));
244       ep->_vl_msg_id = ntohs(VL_API_MEMCLNT_RX_THREAD_SUSPEND);
245       vl_msg_api_send_shmem(am->vl_input_queue, (u8 *)&ep);
246       /* Wait for RX thread to tell us it has suspended */
247       pthread_cond_wait(&pm->suspend_cv, &pm->queue_lock);
248       rx_is_running = false;
249     }
250   pthread_mutex_unlock(&pm->queue_lock);
251 }
252
253 void
254 vac_rx_resume (void)
255 {
256   vac_main_t *pm = &vac_main;
257   if (!pm->rx_thread_handle) return;
258   pthread_mutex_lock(&pm->queue_lock);
259   if (rx_is_running) goto unlock;
260   pthread_cond_signal(&pm->resume_cv);
261   rx_is_running = true;
262  unlock:
263   pthread_mutex_unlock(&pm->queue_lock);
264 }
265
266 static uword *
267 vac_msg_table_get_hash (void)
268 {
269   api_main_t *am = vlibapi_get_main();
270   return (am->msg_index_by_name_and_crc);
271 }
272
273 int
274 vac_msg_table_size(void)
275 {
276   api_main_t *am = vlibapi_get_main();
277   return hash_elts(am->msg_index_by_name_and_crc);
278 }
279
280 int
281 vac_connect (char * name, char * chroot_prefix, vac_callback_t cb,
282              int rx_qlen)
283 {
284   rx_thread_done = false;
285   int rv = 0;
286   vac_main_t *pm = &vac_main;
287
288   assert (clib_mem_get_heap ());
289   init();
290   if (chroot_prefix != NULL)
291     vl_set_memory_root_path (chroot_prefix);
292
293   if ((rv = vl_client_api_map("/vpe-api"))) {
294     clib_warning ("vl_client_api_map returned %d", rv);
295     return rv;
296   }
297
298   if (vl_client_connect(name, 0, rx_qlen) < 0) {
299     vl_client_api_unmap();
300     return (-1);
301   }
302
303   if (cb) {
304     /* Start the rx queue thread */
305     rv = pthread_create(&pm->rx_thread_handle, NULL, vac_rx_thread_fn, 0);
306     if (rv) {
307       clib_warning("pthread_create returned %d", rv);
308       vl_client_api_unmap();
309       return (-1);
310     }
311     vac_callback = cb;
312     rx_is_running = true;
313   }
314
315   /* Start read timeout thread */
316   rv = pthread_create(&pm->timeout_thread_handle, NULL,
317                       vac_timeout_thread_fn, 0);
318   if (rv) {
319     clib_warning("pthread_create returned %d", rv);
320     vl_client_api_unmap();
321     return (-1);
322   }
323
324   pm->connected_to_vlib = 1;
325
326   return (0);
327 }
328 static void
329 set_timeout (unsigned short timeout)
330 {
331   vac_main_t *pm = &vac_main;
332   pthread_mutex_lock(&pm->timeout_lock);
333   read_timeout = timeout;
334   timeout_in_progress = true;
335   timeout_cancelled = false;
336   pthread_cond_signal(&pm->timeout_cv);
337   pthread_mutex_unlock(&pm->timeout_lock);
338 }
339
340 static void
341 unset_timeout (void)
342 {
343   vac_main_t *pm = &vac_main;
344   pthread_mutex_lock(&pm->timeout_lock);
345   timeout_in_progress = false;
346   timeout_cancelled = true;
347   pthread_cond_signal(&pm->timeout_cancel_cv);
348   pthread_mutex_unlock(&pm->timeout_lock);
349 }
350
351 int
352 vac_disconnect (void)
353 {
354   api_main_t *am = vlibapi_get_main();
355   vac_main_t *pm = &vac_main;
356   uword junk;
357   int rv = 0;
358
359   if (!pm->connected_to_vlib) return 0;
360
361   if (pm->rx_thread_handle) {
362     vl_api_rx_thread_exit_t *ep;
363     ep = vl_msg_api_alloc (sizeof (*ep));
364     ep->_vl_msg_id = ntohs(VL_API_RX_THREAD_EXIT);
365     vl_msg_api_send_shmem(am->vl_input_queue, (u8 *)&ep);
366
367     /* wait (with timeout) until RX thread has finished */
368     struct timespec ts;
369     struct timeval tv;
370     gettimeofday(&tv, NULL);
371     ts.tv_sec = tv.tv_sec + 5;
372     ts.tv_nsec = 0;
373
374     pthread_mutex_lock(&pm->queue_lock);
375     if (rx_thread_done == false)
376       rv = pthread_cond_timedwait(&pm->terminate_cv, &pm->queue_lock, &ts);
377     pthread_mutex_unlock(&pm->queue_lock);
378
379     /* now join so we wait until thread has -really- finished */
380     if (rv == ETIMEDOUT)
381       pthread_cancel(pm->rx_thread_handle);
382     else
383       pthread_join(pm->rx_thread_handle, (void **) &junk);
384   }
385   if (pm->timeout_thread_handle) {
386     /* cancel, wake then join the timeout thread */
387     pm->timeout_loop = 0;
388     timeout_thread_cancelled = true;
389     set_timeout(0);
390     pthread_join(pm->timeout_thread_handle, (void **) &junk);
391   }
392
393   vl_client_disconnect();
394   vl_client_api_unmap();
395   //vac_callback = 0;
396
397   cleanup();
398
399   return (0);
400 }
401
402 int
403 vac_read (char **p, int *l, u16 timeout)
404 {
405   svm_queue_t *q;
406   api_main_t *am = vlibapi_get_main();
407   vac_main_t *pm = &vac_main;
408   vl_api_memclnt_keepalive_t *mp;
409   vl_api_memclnt_keepalive_reply_t *rmp;
410   uword msg;
411   msgbuf_t *msgbuf;
412   int rv;
413   vl_shmem_hdr_t *shmem_hdr;
414
415   /* svm_queue_sub(below) returns {-1, -2} */
416   if (!pm->connected_to_vlib)
417     return VAC_NOT_CONNECTED;
418
419   *l = 0;
420
421   /* svm_queue_sub(below) returns {-1, -2} */
422   if (am->our_pid == 0)
423     return (VAC_SHM_NOT_READY);
424
425   /* Poke timeout thread */
426   if (timeout)
427     set_timeout(timeout);
428
429   q = am->vl_input_queue;
430
431  again:
432   rv = svm_queue_sub(q, (u8 *)&msg, SVM_Q_WAIT, 0);
433
434   if (rv == 0) {
435     VL_MSG_API_UNPOISON((void *)msg);
436     u16 msg_id = ntohs(*((u16 *)msg));
437     switch (msg_id) {
438     case VL_API_RX_THREAD_EXIT:
439       vl_msg_api_free((void *) msg);
440       goto error;
441     case VL_API_MEMCLNT_RX_THREAD_SUSPEND:
442       goto error;
443     case VL_API_MEMCLNT_READ_TIMEOUT:
444       goto error;
445     case VL_API_MEMCLNT_KEEPALIVE:
446       /* Handle an alive-check ping from vpp. */
447       mp = (void *)msg;
448       rmp = vl_msg_api_alloc (sizeof (*rmp));
449       clib_memset (rmp, 0, sizeof (*rmp));
450       rmp->_vl_msg_id = ntohs(VL_API_MEMCLNT_KEEPALIVE_REPLY);
451       rmp->context = mp->context;
452       shmem_hdr = am->shmem_hdr;
453       vl_msg_api_send_shmem(shmem_hdr->vl_input_queue, (u8 *)&rmp);
454       vl_msg_api_free((void *) msg);
455       /*
456        * Python code is blissfully unaware of these pings, so
457        * act as if it never happened...
458        */
459       goto again;
460
461     default:
462       msgbuf = (msgbuf_t *)(((u8 *)msg) - offsetof(msgbuf_t, data));
463       *l = ntohl(msgbuf->data_len);
464       if (*l == 0) {
465         fprintf(stderr, "Unregistered API message: %d\n", msg_id);
466         goto error;
467       }
468     }
469     *p = (char *)msg;
470
471
472   } else {
473     fprintf(stderr, "Read failed with %d\n", rv);
474   }
475   /* Let timeout notification thread know we're done */
476   if (timeout)
477     unset_timeout();
478
479   return (rv);
480
481  error:
482   if (timeout)
483     unset_timeout();
484   vl_msg_api_free((void *) msg);
485   /* Client might forget to resume RX thread on failure */
486   vac_rx_resume ();
487   return VAC_TIMEOUT;
488 }
489
490 /*
491  * XXX: Makes the assumption that client_index is the first member
492  */
493 typedef struct _vl_api_header
494 {
495   u16 _vl_msg_id;
496   u32 client_index;
497 } __attribute__ ((packed)) vl_api_header_t;
498
499 static u32
500 vac_client_index (void)
501 {
502   return (vlibapi_get_main()->my_client_index);
503 }
504
505 int
506 vac_write (char *p, int l)
507 {
508   int rv = -1;
509   api_main_t *am = vlibapi_get_main();
510   vl_api_header_t *mp = vl_msg_api_alloc(l);
511   svm_queue_t *q;
512   vac_main_t *pm = &vac_main;
513
514   if (!pm->connected_to_vlib)
515     return VAC_NOT_CONNECTED;
516   if (!mp) return (-1);
517
518   memcpy(mp, p, l);
519   mp->client_index = vac_client_index();
520   q = am->shmem_hdr->vl_input_queue;
521   rv = svm_queue_add(q, (u8 *)&mp, 0);
522   if (rv != 0) {
523     fprintf(stderr, "vpe_api_write fails: %d\n", rv);
524     /* Clear message */
525     vac_free(mp);
526   }
527   return (rv);
528 }
529
530 int
531 vac_get_msg_index (char * name)
532 {
533   return vl_msg_api_get_msg_index ((u8 *)name);
534 }
535
536 int
537 vac_msg_table_max_index(void)
538 {
539   int max = 0;
540   hash_pair_t *hp;
541   uword *h = vac_msg_table_get_hash();
542   hash_foreach_pair (hp, h,
543   ({
544     if (hp->value[0] > max)
545       max = hp->value[0];
546   }));
547
548   return max;
549 }
550
551 void
552 vac_set_error_handler (vac_error_callback_t cb)
553 {
554   assert (clib_mem_get_heap ());
555   if (cb) clib_error_register_handler (cb, 0);
556 }
557
558 /*
559  * Required if application doesn't use a VPP heap.
560  */
561 void
562 vac_mem_init (size_t size)
563 {
564   if (mem_initialized)
565     return;
566   if (size == 0)
567     clib_mem_init (0, 1 << 30);  // default
568   else
569     clib_mem_init (0, size);
570   mem_initialized = true;
571 }