quic: Fix listener vpp_session_handle
[vpp.git] / src / plugins / hs_apps / sapi / vpp_echo.c
1 /*
2  * Copyright (c) 2019 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
16 #include <stdio.h>
17 #include <signal.h>
18
19 #include <vlibmemory/api.h>
20 #include <svm/fifo_segment.h>
21
22 #include <hs_apps/sapi/vpp_echo_common.h>
23
24 echo_main_t echo_main;
25
26 static void
27 echo_session_prealloc (echo_main_t * em)
28 {
29   /* We need to prealloc to avoid vec resize in threads */
30   echo_session_t *session;
31   int i;
32   for (i = 0; i < em->n_sessions; i++)
33     {
34       pool_get (em->sessions, session);
35       clib_memset (session, 0, sizeof (*session));
36       session->session_index = session - em->sessions;
37       session->listener_index = SESSION_INVALID_INDEX;
38       session->session_state = ECHO_SESSION_STATE_INITIAL;
39     }
40 }
41
42 static void
43 echo_assert_test_suceeded (echo_main_t * em)
44 {
45   CHECK (em->n_clients * em->bytes_to_receive,
46          em->stats.rx_total, "Not enough data received");
47   CHECK (em->n_clients * em->bytes_to_send,
48          em->stats.tx_total, "Not enough data sent");
49   clib_spinlock_lock (&em->sid_vpp_handles_lock);
50   CHECK (0, hash_elts (em->session_index_by_vpp_handles),
51          "Some sessions are still open");
52   clib_spinlock_unlock (&em->sid_vpp_handles_lock);
53 }
54
55 always_inline void
56 echo_session_dequeue_notify (echo_session_t * s)
57 {
58   int rv;
59   if (!svm_fifo_set_event (s->rx_fifo))
60     return;
61   if ((rv =
62        app_send_io_evt_to_vpp (s->vpp_evt_q, s->rx_fifo->master_session_index,
63                                SESSION_IO_EVT_RX, SVM_Q_WAIT)))
64     ECHO_FAIL ("app_send_io_evt_to_vpp errored %d", rv);
65   svm_fifo_clear_deq_ntf (s->rx_fifo);
66 }
67
68 static void
69 stop_signal (int signum)
70 {
71   echo_main_t *em = &echo_main;
72   em->time_to_stop = 1;
73 }
74
75 int
76 connect_to_vpp (char *name)
77 {
78   echo_main_t *em = &echo_main;
79   api_main_t *am = &api_main;
80
81   if (em->use_sock_api)
82     {
83       if (vl_socket_client_connect ((char *) em->socket_name, name,
84                                     0 /* default rx, tx buffer */ ))
85         {
86           ECHO_FAIL ("socket connect failed");
87           return -1;
88         }
89
90       if (vl_socket_client_init_shm (0, 1 /* want_pthread */ ))
91         {
92           ECHO_FAIL ("init shm api failed");
93           return -1;
94         }
95     }
96   else
97     {
98       if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
99         {
100           ECHO_FAIL ("shmem connect failed");
101           return -1;
102         }
103     }
104   em->vl_input_queue = am->shmem_hdr->vl_input_queue;
105   em->my_client_index = am->my_client_index;
106   return 0;
107 }
108
109 static void
110 echo_event_didnt_happen (u8 e)
111 {
112   echo_main_t *em = &echo_main;
113   u8 *s = format (0, "%U", echo_format_timing_event, e);
114   ECHO_LOG (0, "Expected event %s to happend, which did not", s);
115   em->has_failed = 1;
116 }
117
118 static void
119 print_global_json_stats (echo_main_t * em)
120 {
121   if (!(em->timing.events_sent & em->timing.start_event))
122     return echo_event_didnt_happen (em->timing.start_event);
123   if (!(em->timing.events_sent & em->timing.end_event))
124     return echo_event_didnt_happen (em->timing.end_event);
125   f64 deltat = em->timing.end_time - em->timing.start_time;
126   u8 *start_evt =
127     format (0, "%U", echo_format_timing_event, em->timing.start_event);
128   u8 *end_evt =
129     format (0, "%U", echo_format_timing_event, em->timing.end_event);
130   fformat (stdout, "{\n");
131   fformat (stdout, "\"time\": \"%.9f\",\n", deltat);
132   fformat (stdout, "\"start_evt\": \"%s\",\n", start_evt);
133   fformat (stdout, "\"end_evt\": \"%s\",\n", end_evt);
134   fformat (stdout, "\"rx_data\": %lld,\n", em->stats.rx_total);
135   fformat (stdout, "\"tx_rx\": %lld,\n", em->stats.tx_total);
136   fformat (stdout, "\"closing\": {\n");
137   fformat (stdout, "  \"reset\": { \"q\": %d, \"s\": %d },\n",
138            em->stats.reset_count.q, em->stats.reset_count.s);
139   fformat (stdout, "  \"close\": { \"q\": %d, \"s\": %d },\n",
140            em->stats.close_count.q, em->stats.close_count.s);
141   fformat (stdout, "  \"active\": { \"q\": %d, \"s\": %d },\n",
142            em->stats.active_count.q, em->stats.active_count.s);
143   fformat (stdout, "  \"clean\": { \"q\": %d, \"s\": %d }\n",
144            em->stats.clean_count.q, em->stats.clean_count.s);
145   fformat (stdout, "}\n");
146   fformat (stdout, "}\n");
147 }
148
149 static void
150 print_global_stats (echo_main_t * em)
151 {
152   u8 *s;
153   if (!(em->timing.events_sent & em->timing.start_event))
154     return echo_event_didnt_happen (em->timing.start_event);
155   if (!(em->timing.events_sent & em->timing.end_event))
156     return echo_event_didnt_happen (em->timing.end_event);
157   f64 deltat = em->timing.end_time - em->timing.start_time;
158   s = format (0, "%U:%U",
159               echo_format_timing_event, em->timing.start_event,
160               echo_format_timing_event, em->timing.end_event);
161   fformat (stdout, "Timing %s\n", s);
162   fformat (stdout, "-------- TX --------\n");
163   fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.6f seconds\n",
164            em->stats.tx_total, em->stats.tx_total / (1ULL << 20),
165            em->stats.tx_total / (1ULL << 30), deltat);
166   fformat (stdout, "%.4f Gbit/second\n",
167            (em->stats.tx_total * 8.0) / deltat / 1e9);
168   fformat (stdout, "-------- RX --------\n");
169   fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.6f seconds\n",
170            em->stats.rx_total, em->stats.rx_total / (1ULL << 20),
171            em->stats.rx_total / (1ULL << 30), deltat);
172   fformat (stdout, "%.4f Gbit/second\n",
173            (em->stats.rx_total * 8.0) / deltat / 1e9);
174   fformat (stdout, "--------------------\n");
175   fformat (stdout, "Received close on %d streams (and %d Quic conn)\n",
176            em->stats.close_count.s, em->stats.close_count.q);
177   fformat (stdout, "Received reset on %d streams (and %d Quic conn)\n",
178            em->stats.reset_count.s, em->stats.reset_count.q);
179   fformat (stdout, "Sent close on     %d streams (and %d Quic conn)\n",
180            em->stats.active_count.s, em->stats.active_count.q);
181   fformat (stdout, "Discarded         %d streams (and %d Quic conn)\n",
182            em->stats.clean_count.s, em->stats.clean_count.q);
183 }
184
185 void
186 echo_update_count_on_session_close (echo_main_t * em, echo_session_t * s)
187 {
188
189   ECHO_LOG (1, "[%lu/%lu] -> S(%x) -> [%lu/%lu]",
190             s->bytes_received, s->bytes_received + s->bytes_to_receive,
191             s->session_index, s->bytes_sent,
192             s->bytes_sent + s->bytes_to_send);
193   clib_atomic_fetch_add (&em->stats.tx_total, s->bytes_sent);
194   clib_atomic_fetch_add (&em->stats.rx_total, s->bytes_received);
195
196   if (PREDICT_FALSE (em->stats.rx_total ==
197                      em->n_clients * em->bytes_to_receive))
198     echo_notify_event (em, ECHO_EVT_LAST_BYTE);
199 }
200
201 static void
202 echo_free_sessions (echo_main_t * em)
203 {
204   /* Free marked sessions */
205   echo_session_t *s;
206   u32 *session_indexes = 0, *session_index;
207
208   /* *INDENT-OFF* */
209   pool_foreach (s, em->sessions,
210   ({
211     if (s->session_state == ECHO_SESSION_STATE_CLOSED)
212       vec_add1 (session_indexes, s->session_index);}
213   ));
214   /* *INDENT-ON* */
215   vec_foreach (session_index, session_indexes)
216   {
217     /* Free session */
218     s = pool_elt_at_index (em->sessions, *session_index);
219     echo_session_handle_add_del (em, s->vpp_session_handle,
220                                  SESSION_INVALID_INDEX);
221     pool_put (em->sessions, s);
222     clib_memset (s, 0xfe, sizeof (*s));
223   }
224 }
225
226 static void
227 test_recv_bytes (echo_main_t * em, echo_session_t * s, u8 * rx_buf,
228                  u32 n_read)
229 {
230   u32 i;
231   u8 expected;
232   for (i = 0; i < n_read; i++)
233     {
234       expected = (s->bytes_received + i) & 0xff;
235       if (rx_buf[i] == expected || em->max_test_msg > 0)
236         continue;
237       ECHO_LOG (0, "Session 0x%lx byte %lld was 0x%x expected 0x%x",
238                 s->vpp_session_handle, s->bytes_received + i, rx_buf[i],
239                 expected);
240       em->max_test_msg--;
241       if (em->max_test_msg == 0)
242         ECHO_LOG (0, "Too many errors, hiding next ones");
243       if (em->test_return_packets == RETURN_PACKETS_ASSERT)
244         ECHO_FAIL ("test-bytes errored");
245     }
246 }
247
248 static int
249 recv_data_chunk (echo_main_t * em, echo_session_t * s, u8 * rx_buf)
250 {
251   int n_read;
252   n_read = app_recv ((app_session_t *) s, rx_buf, vec_len (rx_buf));
253   if (n_read <= 0)
254     return 0;
255   if (svm_fifo_needs_deq_ntf (s->rx_fifo, n_read))
256     echo_session_dequeue_notify (s);
257
258   if (em->test_return_packets)
259     test_recv_bytes (em, s, rx_buf, n_read);
260
261   s->bytes_received += n_read;
262   s->bytes_to_receive -= n_read;
263   return n_read;
264 }
265
266 static int
267 send_data_chunk (echo_session_t * s, u8 * tx_buf, int offset, int len)
268 {
269   int n_sent;
270   int bytes_this_chunk = clib_min (s->bytes_to_send, len - offset);
271   if (!bytes_this_chunk)
272     return 0;
273   n_sent = app_send ((app_session_t *) s, tx_buf + offset,
274                      bytes_this_chunk, SVM_Q_WAIT);
275   if (n_sent < 0)
276     return 0;
277   s->bytes_to_send -= n_sent;
278   s->bytes_sent += n_sent;
279   return n_sent;
280 }
281
282 static int
283 mirror_data_chunk (echo_main_t * em, echo_session_t * s, u8 * tx_buf, u64 len)
284 {
285   u64 n_sent = 0;
286   while (n_sent < len && !em->time_to_stop)
287     n_sent += send_data_chunk (s, tx_buf, n_sent, len);
288   return n_sent;
289 }
290
291 static inline void
292 echo_check_closed_listener (echo_main_t * em, echo_session_t * s)
293 {
294   echo_session_t *ls;
295   /* if parent has died, terminate gracefully */
296   if (s->listener_index == SESSION_INVALID_INDEX)
297     return;
298   ls = pool_elt_at_index (em->sessions, s->listener_index);
299   if (ls->session_state < ECHO_SESSION_STATE_CLOSING)
300     return;
301   ECHO_LOG (2, "Session 0%lx died, close child 0x%lx", ls->vpp_session_handle,
302             s->vpp_session_handle);
303   echo_update_count_on_session_close (em, s);
304   em->proto_cb_vft->cleanup_cb (s, 1 /* parent_died */ );
305 }
306
307 /*
308  * Rx/Tx polling thread per connection
309  */
310 static void
311 echo_handle_data (echo_main_t * em, echo_session_t * s, u8 * rx_buf)
312 {
313   int n_read, n_sent = 0;
314
315   n_read = recv_data_chunk (em, s, rx_buf);
316   if (em->data_source == ECHO_TEST_DATA_SOURCE)
317     n_sent = send_data_chunk (s, em->connect_test_data,
318                               s->bytes_sent % em->tx_buf_size,
319                               em->tx_buf_size);
320   else if (em->data_source == ECHO_RX_DATA_SOURCE)
321     n_sent = mirror_data_chunk (em, s, rx_buf, n_read);
322   if (!s->bytes_to_send && !s->bytes_to_receive)
323     {
324       /* Session is done, need to close */
325       if (s->session_state == ECHO_SESSION_STATE_AWAIT_DATA)
326         s->session_state = ECHO_SESSION_STATE_CLOSING;
327       else
328         {
329           s->session_state = ECHO_SESSION_STATE_AWAIT_CLOSING;
330           if (em->send_stream_disconnects == ECHO_CLOSE_F_ACTIVE)
331             {
332               echo_send_rpc (em, echo_send_disconnect_session,
333                              (void *) s->vpp_session_handle, 0);
334               clib_atomic_fetch_add (&em->stats.active_count.s, 1);
335             }
336           else if (em->send_stream_disconnects == ECHO_CLOSE_F_NONE)
337             {
338               s->session_state = ECHO_SESSION_STATE_CLOSING;
339               clib_atomic_fetch_add (&em->stats.clean_count.s, 1);
340             }
341         }
342       return;
343     }
344
345   /* Check for idle clients */
346   if (em->log_lvl > 1)
347     {
348       if (n_sent || n_read)
349         s->idle_cycles = 0;
350       else if (s->idle_cycles++ == 1e7)
351         {
352           s->idle_cycles = 0;
353           ECHO_LOG (1, "Idle client TX:%dB RX:%dB", s->bytes_to_send,
354                     s->bytes_to_receive);
355           ECHO_LOG (1, "Idle FIFOs TX:%dB RX:%dB",
356                     svm_fifo_max_dequeue (s->tx_fifo),
357                     svm_fifo_max_dequeue (s->rx_fifo));
358           ECHO_LOG (1, "Session 0x%lx state %u", s->vpp_session_handle,
359                     s->session_state);
360         }
361     }
362 }
363
364 static void *
365 echo_data_thread_fn (void *arg)
366 {
367   clib_mem_set_thread_index ();
368   echo_main_t *em = &echo_main;
369   u32 N = em->n_clients;
370   u32 n = (N + em->n_rx_threads - 1) / em->n_rx_threads;
371   u32 idx = (u64) arg;
372   if (n * idx >= N)
373     {
374       ECHO_LOG (1, "Thread %u exiting, no sessions to care for", idx);
375       pthread_exit (0);
376     }
377   u32 thread_n_sessions = clib_min (n, N - n * idx);
378
379   u32 i = 0;
380   u32 n_closed_sessions = 0;
381   u32 session_index;
382   u8 *rx_buf = 0;
383   echo_session_t *s;
384   vec_validate (rx_buf, em->rx_buf_size);
385
386   for (i = 0; !em->time_to_stop; i = (i + 1) % thread_n_sessions)
387     {
388       n_closed_sessions = i == 0 ? 0 : n_closed_sessions;
389       session_index = em->data_thread_args[n * idx + i];
390       if (session_index == SESSION_INVALID_INDEX)
391         continue;
392       s = pool_elt_at_index (em->sessions, session_index);
393       switch (s->session_state)
394         {
395         case ECHO_SESSION_STATE_READY:
396         case ECHO_SESSION_STATE_AWAIT_DATA:
397           echo_handle_data (em, s, rx_buf);
398           echo_check_closed_listener (em, s);
399           break;
400         case ECHO_SESSION_STATE_AWAIT_CLOSING:
401           echo_check_closed_listener (em, s);
402           break;
403         case ECHO_SESSION_STATE_CLOSING:
404           echo_update_count_on_session_close (em, s);
405           em->proto_cb_vft->cleanup_cb (s, 0 /* parent_died */ );
406           break;
407         case ECHO_SESSION_STATE_CLOSED:
408           n_closed_sessions++;
409           break;
410         }
411       if (n_closed_sessions == thread_n_sessions)
412         break;
413     }
414   pthread_exit (0);
415 }
416
417 static void
418 session_bound_handler (session_bound_msg_t * mp)
419 {
420   echo_main_t *em = &echo_main;
421   echo_session_t *listen_session;
422   if (mp->retval)
423     {
424       ECHO_FAIL ("bind failed: %U", format_api_error,
425                  clib_net_to_host_u32 (mp->retval));
426       return;
427     }
428   ECHO_LOG (0, "listening on %U:%u", format_ip46_address, mp->lcl_ip,
429             mp->lcl_is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
430             clib_net_to_host_u16 (mp->lcl_port));
431
432   /* Allocate local session and set it up */
433   listen_session = echo_session_new (em);
434   listen_session->session_type = ECHO_SESSION_TYPE_LISTEN;
435   listen_session->vpp_session_handle = mp->handle;
436   echo_session_handle_add_del (em, mp->handle, listen_session->session_index);
437   em->state = STATE_LISTEN;
438   em->listen_session_index = listen_session->session_index;
439   if (em->proto_cb_vft->bound_uri_cb)
440     em->proto_cb_vft->bound_uri_cb (mp, listen_session);
441 }
442
443 static void
444 session_accepted_handler (session_accepted_msg_t * mp)
445 {
446   app_session_evt_t _app_evt, *app_evt = &_app_evt;
447   session_accepted_reply_msg_t *rmp;
448   svm_fifo_t *rx_fifo, *tx_fifo;
449   echo_main_t *em = &echo_main;
450   echo_session_t *session, *ls;
451   /* Allocate local session and set it up */
452   session = echo_session_new (em);
453
454   if (wait_for_segment_allocation (mp->segment_handle))
455     {
456       ECHO_FAIL ("wait_for_segment_allocation errored");
457       return;
458     }
459
460   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
461   rx_fifo->client_session_index = session->session_index;
462   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
463   tx_fifo->client_session_index = session->session_index;
464
465   session->rx_fifo = rx_fifo;
466   session->tx_fifo = tx_fifo;
467
468   /* session->transport needed by app_send_dgram */
469   clib_memcpy_fast (&session->transport.rmt_ip, &mp->rmt.ip,
470                     sizeof (ip46_address_t));
471   session->transport.is_ip4 = mp->rmt.is_ip4;
472   session->transport.rmt_port = mp->rmt.port;
473   clib_memcpy_fast (&session->transport.lcl_ip, &em->uri_elts.ip,
474                     sizeof (ip46_address_t));
475   session->transport.lcl_port = em->uri_elts.port;
476
477   session->vpp_session_handle = mp->handle;
478   session->start = clib_time_now (&em->clib_time);
479   session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
480                                          svm_msg_q_t *);
481   if (!(ls = echo_get_session_from_handle (em, mp->listener_handle)))
482     return;
483   session->listener_index = ls->session_index;
484
485   /* Add it to lookup table */
486   ECHO_LOG (1, "Accepted session 0x%lx -> 0x%lx", mp->handle,
487             mp->listener_handle);
488   echo_session_handle_add_del (em, mp->handle, session->session_index);
489
490   app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt,
491                              SESSION_CTRL_EVT_ACCEPTED_REPLY);
492   rmp = (session_accepted_reply_msg_t *) app_evt->evt->data;
493   rmp->handle = mp->handle;
494   rmp->context = mp->context;
495   app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt);
496   em->proto_cb_vft->accepted_cb (mp, session);
497 }
498
499 static void
500 session_connected_handler (session_connected_msg_t * mp)
501 {
502   echo_main_t *em = &echo_main;
503   echo_session_t *session;
504   u32 listener_index = htonl (mp->context);
505   svm_fifo_t *rx_fifo, *tx_fifo;
506
507   if (mp->retval)
508     {
509       ECHO_FAIL ("connection failed with code: %U", format_api_error,
510                  clib_net_to_host_u32 (mp->retval));
511       return;
512     }
513
514   session = echo_session_new (em);
515   if (wait_for_segment_allocation (mp->segment_handle))
516     {
517       ECHO_FAIL ("wait_for_segment_allocation errored");
518       return;
519     }
520
521   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
522   rx_fifo->client_session_index = session->session_index;
523   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
524   tx_fifo->client_session_index = session->session_index;
525
526   session->rx_fifo = rx_fifo;
527   session->tx_fifo = tx_fifo;
528   session->vpp_session_handle = mp->handle;
529   session->start = clib_time_now (&em->clib_time);
530   session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
531                                          svm_msg_q_t *);
532   session->listener_index = listener_index;
533   /* session->transport needed by app_send_dgram */
534   clib_memcpy_fast (&session->transport.lcl_ip, &mp->lcl.ip,
535                     sizeof (ip46_address_t));
536   session->transport.is_ip4 = mp->lcl.is_ip4;
537   session->transport.lcl_port = mp->lcl.port;
538   clib_memcpy_fast (&session->transport.rmt_ip, &em->uri_elts.ip,
539                     sizeof (ip46_address_t));
540   session->transport.rmt_port = em->uri_elts.port;
541
542   echo_session_handle_add_del (em, mp->handle, session->session_index);
543   em->proto_cb_vft->connected_cb ((session_connected_bundled_msg_t *) mp,
544                                   session->session_index, 0 /* is_failed */ );
545 }
546
547 /*
548  *
549  *  End of ECHO callback definitions
550  *
551  */
552
553 static void
554 session_disconnected_handler (session_disconnected_msg_t * mp)
555 {
556   app_session_evt_t _app_evt, *app_evt = &_app_evt;
557   session_disconnected_reply_msg_t *rmp;
558   echo_main_t *em = &echo_main;
559   echo_session_t *s;
560   ECHO_LOG (1, "passive close session 0x%lx", mp->handle);
561   if (!(s = echo_get_session_from_handle (em, mp->handle)))
562     return;
563   em->proto_cb_vft->disconnected_cb (mp, s);
564
565   app_alloc_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt,
566                              SESSION_CTRL_EVT_DISCONNECTED_REPLY);
567   rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data;
568   rmp->retval = 0;
569   rmp->handle = mp->handle;
570   rmp->context = mp->context;
571   app_send_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt);
572 }
573
574 static void
575 session_reset_handler (session_reset_msg_t * mp)
576 {
577   app_session_evt_t _app_evt, *app_evt = &_app_evt;
578   echo_main_t *em = &echo_main;
579   session_reset_reply_msg_t *rmp;
580   echo_session_t *s = 0;
581   ECHO_LOG (1, "Reset session 0x%lx", mp->handle);
582   if (!(s = echo_get_session_from_handle (em, mp->handle)))
583     return;
584   em->proto_cb_vft->reset_cb (mp, s);
585
586   app_alloc_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt,
587                              SESSION_CTRL_EVT_RESET_REPLY);
588   rmp = (session_reset_reply_msg_t *) app_evt->evt->data;
589   rmp->retval = 0;
590   rmp->handle = mp->handle;
591   app_send_ctrl_evt_to_vpp (s->vpp_evt_q, app_evt);
592 }
593
594 static void
595 handle_mq_event (session_event_t * e)
596 {
597   switch (e->event_type)
598     {
599     case SESSION_CTRL_EVT_BOUND:
600       session_bound_handler ((session_bound_msg_t *) e->data);
601       break;
602     case SESSION_CTRL_EVT_ACCEPTED:
603       session_accepted_handler ((session_accepted_msg_t *) e->data);
604       break;
605     case SESSION_CTRL_EVT_CONNECTED:
606       session_connected_handler ((session_connected_msg_t *) e->data);
607       break;
608     case SESSION_CTRL_EVT_DISCONNECTED:
609       session_disconnected_handler ((session_disconnected_msg_t *) e->data);
610       break;
611     case SESSION_CTRL_EVT_RESET:
612       session_reset_handler ((session_reset_msg_t *) e->data);
613       break;
614     case SESSION_IO_EVT_RX:
615       break;
616     default:
617       ECHO_LOG (0, "unhandled event %u", e->event_type);
618     }
619 }
620
621 static void
622 echo_process_rpcs (echo_main_t * em)
623 {
624   echo_rpc_msg_t *rpc;
625   svm_msg_q_msg_t msg;
626   while (em->state < STATE_DATA_DONE && !em->time_to_stop)
627     {
628       if (svm_msg_q_sub (em->rpc_msq_queue, &msg, SVM_Q_TIMEDWAIT, 1))
629         continue;
630       rpc = svm_msg_q_msg_data (em->rpc_msq_queue, &msg);
631       ((echo_rpc_t) rpc->fp) (rpc->arg, rpc->opaque);
632       svm_msg_q_free_msg (em->rpc_msq_queue, &msg);
633     }
634 }
635
636 static void *
637 echo_mq_thread_fn (void *arg)
638 {
639   clib_mem_set_thread_index ();
640   echo_main_t *em = &echo_main;
641   session_event_t *e;
642   svm_msg_q_msg_t msg;
643   int rv;
644   wait_for_state_change (em, STATE_ATTACHED, 0);
645   if (em->state < STATE_ATTACHED || !em->our_event_queue)
646     {
647       ECHO_FAIL ("Application failed to attach");
648       pthread_exit (0);
649     }
650
651   while (1)
652     {
653       if (!(rv = svm_msg_q_sub (em->our_event_queue,
654                                 &msg, SVM_Q_TIMEDWAIT, 1)))
655         {
656           e = svm_msg_q_msg_data (em->our_event_queue, &msg);
657           handle_mq_event (e);
658           svm_msg_q_free_msg (em->our_event_queue, &msg);
659         }
660       if (rv == ETIMEDOUT
661           && (em->time_to_stop || em->state == STATE_DETACHED))
662         break;
663     }
664   pthread_exit (0);
665 }
666
667 static void
668 clients_run (echo_main_t * em)
669 {
670   u64 i;
671   echo_notify_event (em, ECHO_EVT_FIRST_QCONNECT);
672   for (i = 0; i < em->n_connects; i++)
673     echo_send_connect (em->uri, SESSION_INVALID_INDEX);
674   wait_for_state_change (em, STATE_READY, 0);
675   ECHO_LOG (1, "App is ready");
676   echo_process_rpcs (em);
677 }
678
679 static void
680 server_run (echo_main_t * em)
681 {
682   echo_send_listen (em);
683   wait_for_state_change (em, STATE_READY, 0);
684   ECHO_LOG (1, "App is ready");
685   echo_process_rpcs (em);
686   /* Cleanup */
687   echo_send_unbind (em);
688   if (wait_for_state_change (em, STATE_DISCONNECTED, TIMEOUT))
689     {
690       ECHO_FAIL ("Timeout waiting for state disconnected");
691       return;
692     }
693 }
694
695 static void
696 print_usage_and_exit (void)
697 {
698   echo_main_t *em = &echo_main;
699   int i;
700   fprintf (stderr,
701            "Usage: vpp_echo [socket-name SOCKET] [client|server] [uri URI] [OPTIONS]\n"
702            "Generates traffic and assert correct teardown of the QUIC hoststack\n"
703            "\n"
704            "  socket-name PATH    Specify the binary socket path to connect to VPP\n"
705            "  use-svm-api         Use SVM API to connect to VPP\n"
706            "  test-bytes[:assert] Check data correctness when receiving (assert fails on first error)\n"
707            "  fifo-size N         Use N Kb fifos\n"
708            "  rx-buf N            Use N Kb RX buffer\n"
709            "  tx-buf N            Use N Kb TX test buffer\n"
710            "  appns NAMESPACE     Use the namespace NAMESPACE\n"
711            "  all-scope           all-scope option\n"
712            "  local-scope         local-scope option\n"
713            "  global-scope        global-scope option\n"
714            "  secret SECRET       set namespace secret\n"
715            "  chroot prefix PATH  Use PATH as memory root path\n"
716            "  sclose=[Y|N|W]      When a stream is done,    pass[N] send[Y] or wait[W] for close\n"
717            "\n"
718            "  time START:END      Time between evts START & END, events being :\n"
719            "                       start - Start of the app\n"
720            "                       qconnect    - first Connection connect sent\n"
721            "                       qconnected  - last Connection connected\n"
722            "                       sconnect    - first Stream connect sent\n"
723            "                       sconnected  - last Stream got connected\n"
724            "                       lastbyte    - Last expected byte received\n"
725            "                       exit        - Exiting of the app\n"
726            "  json                Output global stats in json\n"
727            "  log=N               Set the log level to [0: no output, 1:errors, 2:log]\n"
728            "\n"
729            "  nclients N          Open N clients sending data\n"
730            "  nthreads N          Use N busy loop threads for data [in addition to main & msg queue]\n"
731            "  TX=1337[Kb|Mb|GB]   Send 1337 [K|M|G]bytes, use TX=RX to reflect the data\n"
732            "  RX=1337[Kb|Mb|GB]   Expect 1337 [K|M|G]bytes\n" "\n");
733   for (i = 0; i < TRANSPORT_N_PROTO; i++)
734     {
735       echo_proto_cb_vft_t *vft = em->available_proto_cb_vft[i];
736       if (vft && vft->print_usage_cb)
737         vft->print_usage_cb ();
738     }
739   fprintf (stderr, "\nDefault configuration is :\n"
740            " server nclients 1/1 RX=64Kb TX=RX\n"
741            " client nclients 1/1 RX=64Kb TX=64Kb\n");
742   exit (1);
743 }
744
745 static int
746 echo_process_each_proto_opts (unformat_input_t * a)
747 {
748   echo_main_t *em = &echo_main;
749   int i, rv;
750   for (i = 0; i < TRANSPORT_N_PROTO; i++)
751     {
752       echo_proto_cb_vft_t *vft = em->available_proto_cb_vft[i];
753       if (vft && vft->process_opts_cb)
754         if ((rv = vft->process_opts_cb (a)))
755           return rv;
756     }
757   return 0;
758 }
759
760 static void
761 echo_set_each_proto_defaults_before_opts (echo_main_t * em)
762 {
763   int i;
764   for (i = 0; i < TRANSPORT_N_PROTO; i++)
765     {
766       echo_proto_cb_vft_t *vft = em->available_proto_cb_vft[i];
767       if (vft && vft->set_defaults_before_opts_cb)
768         vft->set_defaults_before_opts_cb ();
769     }
770 }
771
772 void
773 echo_process_opts (int argc, char **argv)
774 {
775   echo_main_t *em = &echo_main;
776   unformat_input_t _argv, *a = &_argv;
777   u32 tmp;
778   u8 *chroot_prefix;
779   u8 *uri = 0;
780   u8 default_f_active;
781
782   unformat_init_command_line (a, argv);
783   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
784     {
785       if (echo_process_each_proto_opts (a))
786         ;
787       else if (unformat (a, "chroot prefix %s", &chroot_prefix))
788         vl_set_memory_root_path ((char *) chroot_prefix);
789       else if (unformat (a, "uri %s", &uri))
790         em->uri = format (0, "%s%c", uri, 0);
791       else if (unformat (a, "server"))
792         em->i_am_master = 1;
793       else if (unformat (a, "client"))
794         em->i_am_master = 0;
795       else if (unformat (a, "test-bytes:assert"))
796         em->test_return_packets = RETURN_PACKETS_ASSERT;
797       else if (unformat (a, "test-bytes"))
798         em->test_return_packets = RETURN_PACKETS_LOG_WRONG;
799       else if (unformat (a, "socket-name %s", &em->socket_name))
800         ;
801       else if (unformat (a, "use-svm-api"))
802         em->use_sock_api = 0;
803       else if (unformat (a, "fifo-size %d", &tmp))
804         em->fifo_size = tmp << 10;
805       else if (unformat (a, "rx-buf %d", &tmp))
806         em->rx_buf_size = tmp << 10;
807       else if (unformat (a, "tx-buf %d", &tmp))
808         em->rx_buf_size = tmp << 10;
809       else if (unformat (a, "nclients %d", &em->n_clients))
810         {
811           em->n_sessions = em->n_clients + 1;
812           em->n_connects = em->n_clients;
813         }
814       else if (unformat (a, "nthreads %d", &em->n_rx_threads))
815         ;
816       else if (unformat (a, "appns %_%v%_", &em->appns_id))
817         ;
818       else if (unformat (a, "all-scope"))
819         em->appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE
820                             | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE);
821       else if (unformat (a, "local-scope"))
822         em->appns_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
823       else if (unformat (a, "global-scope"))
824         em->appns_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
825       else if (unformat (a, "secret %lu", &em->appns_secret))
826         ;
827       else if (unformat (a, "TX=RX"))
828         em->data_source = ECHO_RX_DATA_SOURCE;
829       else if (unformat (a, "TX=%U", unformat_data, &em->bytes_to_send))
830         ;
831       else if (unformat (a, "RX=%U", unformat_data, &em->bytes_to_receive))
832         ;
833       else if (unformat (a, "json"))
834         em->output_json = 1;
835       else if (unformat (a, "log=%d", &em->log_lvl))
836         ;
837       else if (unformat (a, "sclose=%U",
838                          echo_unformat_close, &em->send_stream_disconnects))
839         ;
840       else if (unformat (a, "time %U:%U",
841                          echo_unformat_timing_event, &em->timing.start_event,
842                          echo_unformat_timing_event, &em->timing.end_event))
843         ;
844       else
845         print_usage_and_exit ();
846     }
847
848   /* setting default for unset values
849    *
850    * bytes_to_send / bytes_to_receive & data_source  */
851   if (em->bytes_to_receive == (u64) ~ 0)
852     em->bytes_to_receive = 64 << 10;    /* default */
853   if (em->bytes_to_send == (u64) ~ 0)
854     em->bytes_to_send = 64 << 10;       /* default */
855   else if (em->bytes_to_send == 0)
856     em->data_source = ECHO_NO_DATA_SOURCE;
857   else
858     em->data_source = ECHO_TEST_DATA_SOURCE;
859
860   if (em->data_source == ECHO_INVALID_DATA_SOURCE)
861     em->data_source =
862       em->i_am_master ? ECHO_RX_DATA_SOURCE : ECHO_TEST_DATA_SOURCE;
863   if (em->data_source == ECHO_RX_DATA_SOURCE)
864     em->bytes_to_send = em->bytes_to_receive;
865
866   /* disconnect flags  */
867   if (em->i_am_master)
868     default_f_active =
869       em->bytes_to_send == 0 ? ECHO_CLOSE_F_ACTIVE : ECHO_CLOSE_F_PASSIVE;
870   else
871     default_f_active =
872       em->bytes_to_receive == 0 ? ECHO_CLOSE_F_PASSIVE : ECHO_CLOSE_F_ACTIVE;
873   if (em->send_stream_disconnects == ECHO_CLOSE_F_INVALID)
874     em->send_stream_disconnects = default_f_active;
875 }
876
877 void
878 echo_process_uri (echo_main_t * em)
879 {
880   unformat_input_t _input, *input = &_input;
881   u32 port;
882   unformat_init_string (input, (char *) em->uri, strlen ((char *) em->uri));
883   if (unformat
884       (input, "%U://%U/%d", unformat_transport_proto,
885        &em->uri_elts.transport_proto, unformat_ip4_address,
886        &em->uri_elts.ip.ip4, &port))
887     em->uri_elts.is_ip4 = 1;
888   else
889     if (unformat
890         (input, "%U://%U/%d", unformat_transport_proto,
891          &em->uri_elts.transport_proto, unformat_ip6_address,
892          &em->uri_elts.ip.ip6, &port))
893     em->uri_elts.is_ip4 = 0;
894   else
895     ECHO_FAIL ("Unable to process uri");
896   em->uri_elts.port = clib_host_to_net_u16 (port);
897   unformat_free (input);
898 }
899
900 static void __clib_constructor
901 vpp_echo_init ()
902 {
903   /* init memory before proto register themselves */
904   echo_main_t *em = &echo_main;
905   clib_mem_init_thread_safe (0, 256 << 20);
906   clib_memset (em, 0, sizeof (*em));
907 }
908
909 int
910 main (int argc, char **argv)
911 {
912   echo_main_t *em = &echo_main;
913   fifo_segment_main_t *sm = &em->segment_main;
914   char *app_name;
915   u64 i;
916   svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
917   u32 rpc_queue_size = 64 << 10;
918
919   em->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
920   clib_spinlock_init (&em->sid_vpp_handles_lock);
921   em->shared_segment_handles = hash_create (0, sizeof (uword));
922   clib_spinlock_init (&em->segment_handles_lock);
923   em->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0);
924   em->use_sock_api = 1;
925   em->fifo_size = 64 << 10;
926   em->n_clients = 1;
927   em->n_connects = 1;
928   em->n_sessions = 2;
929   em->max_test_msg = 50;
930   em->time_to_stop = 0;
931   em->i_am_master = 1;
932   em->n_rx_threads = 4;
933   em->test_return_packets = RETURN_PACKETS_NOTEST;
934   em->timing.start_event = ECHO_EVT_FIRST_QCONNECT;
935   em->timing.end_event = ECHO_EVT_LAST_BYTE;
936   em->bytes_to_receive = ~0;    /* defaulted when we know if server/client */
937   em->bytes_to_send = ~0;       /* defaulted when we know if server/client */
938   em->rx_buf_size = 1 << 20;
939   em->tx_buf_size = 1 << 20;
940   em->data_source = ECHO_INVALID_DATA_SOURCE;
941   em->uri = format (0, "%s%c", "tcp://0.0.0.0/1234", 0);
942   echo_set_each_proto_defaults_before_opts (em);
943   echo_process_opts (argc, argv);
944   echo_process_uri (em);
945   em->proto_cb_vft = em->available_proto_cb_vft[em->uri_elts.transport_proto];
946   if (!em->proto_cb_vft)
947     {
948       ECHO_FAIL ("Protocol %U is not supported",
949                  format_transport_proto, em->uri_elts.transport_proto);
950       exit (1);
951     }
952   if (em->proto_cb_vft->set_defaults_after_opts_cb)
953     em->proto_cb_vft->set_defaults_after_opts_cb ();
954
955   vec_validate (em->data_thread_handles, em->n_rx_threads);
956   vec_validate (em->data_thread_args, em->n_clients);
957   for (i = 0; i < em->n_clients; i++)
958     em->data_thread_args[i] = SESSION_INVALID_INDEX;
959   clib_time_init (&em->clib_time);
960   init_error_string_table ();
961   fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20);
962   vec_validate (em->connect_test_data, em->tx_buf_size);
963   for (i = 0; i < em->tx_buf_size; i++)
964     em->connect_test_data[i] = i & 0xff;
965
966   /* *INDENT-OFF* */
967   svm_msg_q_ring_cfg_t rc[1] = {
968     {rpc_queue_size, sizeof (echo_rpc_msg_t), 0},
969   };
970   /* *INDENT-ON* */
971   cfg->consumer_pid = getpid ();
972   cfg->n_rings = 1;
973   cfg->q_nitems = rpc_queue_size;
974   cfg->ring_cfgs = rc;
975   em->rpc_msq_queue = svm_msg_q_alloc (cfg);
976
977   signal (SIGINT, stop_signal);
978   signal (SIGQUIT, stop_signal);
979   signal (SIGTERM, stop_signal);
980   echo_api_hookup (em);
981
982   app_name = em->i_am_master ? "echo_server" : "echo_client";
983   if (connect_to_vpp (app_name))
984     {
985       svm_region_exit ();
986       ECHO_FAIL ("Couldn't connect to vpe, exiting...\n");
987       exit (1);
988     }
989
990   echo_session_prealloc (em);
991   echo_notify_event (em, ECHO_EVT_START);
992
993   echo_send_attach (em);
994   if (wait_for_state_change (em, STATE_ATTACHED, TIMEOUT))
995     {
996       ECHO_FAIL ("Couldn't attach to vpp, did you run <session enable> ?\n");
997       exit (1);
998     }
999   if (pthread_create (&em->mq_thread_handle,
1000                       NULL /*attr */ , echo_mq_thread_fn, 0))
1001     {
1002       ECHO_FAIL ("pthread create errored\n");
1003       exit (1);
1004     }
1005   for (i = 0; i < em->n_rx_threads; i++)
1006     if (pthread_create (&em->data_thread_handles[i],
1007                         NULL /*attr */ , echo_data_thread_fn, (void *) i))
1008       {
1009         ECHO_FAIL ("pthread create errored\n");
1010         exit (1);
1011       }
1012   if (em->i_am_master)
1013     server_run (em);
1014   else
1015     clients_run (em);
1016   echo_notify_event (em, ECHO_EVT_EXIT);
1017   if (em->output_json)
1018     print_global_json_stats (em);
1019   else
1020     print_global_stats (em);
1021   echo_free_sessions (em);
1022   echo_assert_test_suceeded (em);
1023   echo_send_detach (em);
1024   if (wait_for_state_change (em, STATE_DETACHED, TIMEOUT))
1025     {
1026       ECHO_FAIL ("ECHO-ERROR: Couldn't detach from vpp, exiting...\n");
1027       exit (1);
1028     }
1029   int *rv;
1030   pthread_join (em->mq_thread_handle, (void **) &rv);
1031   if (rv)
1032     {
1033       ECHO_FAIL ("mq pthread errored %d", rv);
1034       exit (1);
1035     }
1036   if (em->use_sock_api)
1037     vl_socket_client_disconnect ();
1038   else
1039     vl_client_disconnect_from_vlib ();
1040   ECHO_LOG (0, "Test complete !\n");
1041   exit (em->has_failed);
1042 }
1043
1044 /*
1045  * fd.io coding-style-patch-verification: ON
1046  *
1047  * Local Variables:
1048  * eval: (c-set-style "gnu")
1049  * End:
1050  */