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