session: Use parent_handle instead of transport_opts
[vpp.git] / src / plugins / hs_apps / echo_client.c
1 /*
2  * echo_client.c - vpp built-in echo client code
3  *
4  * Copyright (c) 2017-2019 by Cisco and/or its affiliates.
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <vnet/vnet.h>
19 #include <vlibapi/api.h>
20 #include <vlibmemory/api.h>
21 #include <hs_apps/echo_client.h>
22
23 echo_client_main_t echo_client_main;
24
25 #define ECHO_CLIENT_DBG (0)
26 #define DBG(_fmt, _args...)                     \
27     if (ECHO_CLIENT_DBG)                                \
28       clib_warning (_fmt, ##_args)
29
30 static void
31 signal_evt_to_cli_i (int *code)
32 {
33   echo_client_main_t *ecm = &echo_client_main;
34   ASSERT (vlib_get_thread_index () == 0);
35   vlib_process_signal_event (ecm->vlib_main, ecm->cli_node_index, *code, 0);
36 }
37
38 static void
39 signal_evt_to_cli (int code)
40 {
41   if (vlib_get_thread_index () != 0)
42     vl_api_rpc_call_main_thread (signal_evt_to_cli_i, (u8 *) & code,
43                                  sizeof (code));
44   else
45     signal_evt_to_cli_i (&code);
46 }
47
48 static void
49 send_data_chunk (echo_client_main_t * ecm, eclient_session_t * s)
50 {
51   u8 *test_data = ecm->connect_test_data;
52   int test_buf_len, test_buf_offset, rv;
53   u32 bytes_this_chunk;
54
55   test_buf_len = vec_len (test_data);
56   ASSERT (test_buf_len > 0);
57   test_buf_offset = s->bytes_sent % test_buf_len;
58   bytes_this_chunk = clib_min (test_buf_len - test_buf_offset,
59                                s->bytes_to_send);
60
61   if (!ecm->is_dgram)
62     {
63       if (ecm->no_copy)
64         {
65           svm_fifo_t *f = s->data.tx_fifo;
66           rv = clib_min (svm_fifo_max_enqueue_prod (f), bytes_this_chunk);
67           svm_fifo_enqueue_nocopy (f, rv);
68           session_send_io_evt_to_thread_custom (&f->master_session_index,
69                                                 s->thread_index,
70                                                 SESSION_IO_EVT_TX);
71         }
72       else
73         rv = app_send_stream (&s->data, test_data + test_buf_offset,
74                               bytes_this_chunk, 0);
75     }
76   else
77     {
78       if (ecm->no_copy)
79         {
80           session_dgram_hdr_t hdr;
81           svm_fifo_t *f = s->data.tx_fifo;
82           app_session_transport_t *at = &s->data.transport;
83           u32 max_enqueue = svm_fifo_max_enqueue_prod (f);
84
85           if (max_enqueue <= sizeof (session_dgram_hdr_t))
86             return;
87
88           max_enqueue -= sizeof (session_dgram_hdr_t);
89           rv = clib_min (max_enqueue, bytes_this_chunk);
90
91           hdr.data_length = rv;
92           hdr.data_offset = 0;
93           clib_memcpy_fast (&hdr.rmt_ip, &at->rmt_ip,
94                             sizeof (ip46_address_t));
95           hdr.is_ip4 = at->is_ip4;
96           hdr.rmt_port = at->rmt_port;
97           clib_memcpy_fast (&hdr.lcl_ip, &at->lcl_ip,
98                             sizeof (ip46_address_t));
99           hdr.lcl_port = at->lcl_port;
100           svm_fifo_enqueue (f, sizeof (hdr), (u8 *) & hdr);
101           svm_fifo_enqueue_nocopy (f, rv);
102           session_send_io_evt_to_thread_custom (&f->master_session_index,
103                                                 s->thread_index,
104                                                 SESSION_IO_EVT_TX);
105         }
106       else
107         rv = app_send_dgram (&s->data, test_data + test_buf_offset,
108                              bytes_this_chunk, 0);
109     }
110
111   /* If we managed to enqueue data... */
112   if (rv > 0)
113     {
114       /* Account for it... */
115       s->bytes_to_send -= rv;
116       s->bytes_sent += rv;
117
118       if (ECHO_CLIENT_DBG)
119         {
120           /* *INDENT-OFF* */
121           ELOG_TYPE_DECLARE (e) =
122             {
123               .format = "tx-enq: xfer %d bytes, sent %u remain %u",
124               .format_args = "i4i4i4",
125             };
126           /* *INDENT-ON* */
127           struct
128           {
129             u32 data[3];
130           } *ed;
131           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
132           ed->data[0] = rv;
133           ed->data[1] = s->bytes_sent;
134           ed->data[2] = s->bytes_to_send;
135         }
136     }
137 }
138
139 static void
140 receive_data_chunk (echo_client_main_t * ecm, eclient_session_t * s)
141 {
142   svm_fifo_t *rx_fifo = s->data.rx_fifo;
143   u32 thread_index = vlib_get_thread_index ();
144   int n_read, i;
145
146   if (ecm->test_bytes)
147     {
148       if (!ecm->is_dgram)
149         n_read = app_recv_stream (&s->data, ecm->rx_buf[thread_index],
150                                   vec_len (ecm->rx_buf[thread_index]));
151       else
152         n_read = app_recv_dgram (&s->data, ecm->rx_buf[thread_index],
153                                  vec_len (ecm->rx_buf[thread_index]));
154     }
155   else
156     {
157       n_read = svm_fifo_max_dequeue_cons (rx_fifo);
158       svm_fifo_dequeue_drop (rx_fifo, n_read);
159     }
160
161   if (n_read > 0)
162     {
163       if (ECHO_CLIENT_DBG)
164         {
165           /* *INDENT-OFF* */
166           ELOG_TYPE_DECLARE (e) =
167             {
168               .format = "rx-deq: %d bytes",
169               .format_args = "i4",
170             };
171           /* *INDENT-ON* */
172           struct
173           {
174             u32 data[1];
175           } *ed;
176           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
177           ed->data[0] = n_read;
178         }
179
180       if (ecm->test_bytes)
181         {
182           for (i = 0; i < n_read; i++)
183             {
184               if (ecm->rx_buf[thread_index][i]
185                   != ((s->bytes_received + i) & 0xff))
186                 {
187                   clib_warning ("read %d error at byte %lld, 0x%x not 0x%x",
188                                 n_read, s->bytes_received + i,
189                                 ecm->rx_buf[thread_index][i],
190                                 ((s->bytes_received + i) & 0xff));
191                   ecm->test_failed = 1;
192                 }
193             }
194         }
195       ASSERT (n_read <= s->bytes_to_receive);
196       s->bytes_to_receive -= n_read;
197       s->bytes_received += n_read;
198     }
199 }
200
201 static uword
202 echo_client_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
203                      vlib_frame_t * frame)
204 {
205   echo_client_main_t *ecm = &echo_client_main;
206   int my_thread_index = vlib_get_thread_index ();
207   eclient_session_t *sp;
208   int i;
209   int delete_session;
210   u32 *connection_indices;
211   u32 *connections_this_batch;
212   u32 nconnections_this_batch;
213
214   connection_indices = ecm->connection_index_by_thread[my_thread_index];
215   connections_this_batch =
216     ecm->connections_this_batch_by_thread[my_thread_index];
217
218   if ((ecm->run_test != ECHO_CLIENTS_RUNNING) ||
219       ((vec_len (connection_indices) == 0)
220        && vec_len (connections_this_batch) == 0))
221     return 0;
222
223   /* Grab another pile of connections */
224   if (PREDICT_FALSE (vec_len (connections_this_batch) == 0))
225     {
226       nconnections_this_batch =
227         clib_min (ecm->connections_per_batch, vec_len (connection_indices));
228
229       ASSERT (nconnections_this_batch > 0);
230       vec_validate (connections_this_batch, nconnections_this_batch - 1);
231       clib_memcpy_fast (connections_this_batch,
232                         connection_indices + vec_len (connection_indices)
233                         - nconnections_this_batch,
234                         nconnections_this_batch * sizeof (u32));
235       _vec_len (connection_indices) -= nconnections_this_batch;
236     }
237
238   if (PREDICT_FALSE (ecm->prev_conns != ecm->connections_per_batch
239                      && ecm->prev_conns == vec_len (connections_this_batch)))
240     {
241       ecm->repeats++;
242       ecm->prev_conns = vec_len (connections_this_batch);
243       if (ecm->repeats == 500000)
244         {
245           clib_warning ("stuck clients");
246         }
247     }
248   else
249     {
250       ecm->prev_conns = vec_len (connections_this_batch);
251       ecm->repeats = 0;
252     }
253
254   for (i = 0; i < vec_len (connections_this_batch); i++)
255     {
256       delete_session = 1;
257
258       sp = pool_elt_at_index (ecm->sessions, connections_this_batch[i]);
259
260       if (sp->bytes_to_send > 0)
261         {
262           send_data_chunk (ecm, sp);
263           delete_session = 0;
264         }
265       if (sp->bytes_to_receive > 0)
266         {
267           delete_session = 0;
268         }
269       if (PREDICT_FALSE (delete_session == 1))
270         {
271           session_t *s;
272
273           clib_atomic_fetch_add (&ecm->tx_total, sp->bytes_sent);
274           clib_atomic_fetch_add (&ecm->rx_total, sp->bytes_received);
275           s = session_get_from_handle_if_valid (sp->vpp_session_handle);
276
277           if (s)
278             {
279               vnet_disconnect_args_t _a, *a = &_a;
280               a->handle = session_handle (s);
281               a->app_index = ecm->app_index;
282               vnet_disconnect_session (a);
283
284               vec_delete (connections_this_batch, 1, i);
285               i--;
286               clib_atomic_fetch_add (&ecm->ready_connections, -1);
287             }
288           else
289             {
290               clib_warning ("session AWOL?");
291               vec_delete (connections_this_batch, 1, i);
292             }
293
294           /* Kick the debug CLI process */
295           if (ecm->ready_connections == 0)
296             {
297               signal_evt_to_cli (2);
298             }
299         }
300     }
301
302   ecm->connection_index_by_thread[my_thread_index] = connection_indices;
303   ecm->connections_this_batch_by_thread[my_thread_index] =
304     connections_this_batch;
305   return 0;
306 }
307
308 /* *INDENT-OFF* */
309 VLIB_REGISTER_NODE (echo_clients_node) =
310 {
311   .function = echo_client_node_fn,
312   .name = "echo-clients",
313   .type = VLIB_NODE_TYPE_INPUT,
314   .state = VLIB_NODE_STATE_DISABLED,
315 };
316 /* *INDENT-ON* */
317
318 static int
319 create_api_loopback (echo_client_main_t * ecm)
320 {
321   api_main_t *am = &api_main;
322   vl_shmem_hdr_t *shmem_hdr;
323
324   shmem_hdr = am->shmem_hdr;
325   ecm->vl_input_queue = shmem_hdr->vl_input_queue;
326   ecm->my_client_index = vl_api_memclnt_create_internal ("echo_client",
327                                                          ecm->vl_input_queue);
328   return 0;
329 }
330
331 static int
332 echo_clients_init (vlib_main_t * vm)
333 {
334   echo_client_main_t *ecm = &echo_client_main;
335   vlib_thread_main_t *vtm = vlib_get_thread_main ();
336   u32 num_threads;
337   int i;
338
339   if (create_api_loopback (ecm))
340     return -1;
341
342   num_threads = 1 /* main thread */  + vtm->n_threads;
343
344   /* Init test data. Big buffer */
345   vec_validate (ecm->connect_test_data, 4 * 1024 * 1024 - 1);
346   for (i = 0; i < vec_len (ecm->connect_test_data); i++)
347     ecm->connect_test_data[i] = i & 0xff;
348
349   vec_validate (ecm->rx_buf, num_threads - 1);
350   for (i = 0; i < num_threads; i++)
351     vec_validate (ecm->rx_buf[i], vec_len (ecm->connect_test_data) - 1);
352
353   ecm->is_init = 1;
354
355   vec_validate (ecm->connection_index_by_thread, vtm->n_vlib_mains);
356   vec_validate (ecm->connections_this_batch_by_thread, vtm->n_vlib_mains);
357   vec_validate (ecm->quic_session_index_by_thread, vtm->n_vlib_mains);
358   vec_validate (ecm->vpp_event_queue, vtm->n_vlib_mains);
359
360   return 0;
361 }
362
363 static int
364 quic_echo_clients_qsession_connected_callback (u32 app_index, u32 api_context,
365                                                session_t * s, u8 is_fail)
366 {
367   echo_client_main_t *ecm = &echo_client_main;
368   vnet_connect_args_t *a = 0;
369   int rv;
370   u8 thread_index = vlib_get_thread_index ();
371   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
372   u32 stream_n;
373
374   DBG ("QUIC Connection handle %d", session_handle (s));
375
376   vec_validate (a, 1);
377   a->uri = (char *) ecm->connect_uri;
378   parse_uri (a->uri, &sep);
379   sep.parent_handle = session_handle (s);
380
381   for (stream_n = 0; stream_n < ecm->quic_streams; stream_n++)
382     {
383       clib_memset (a, 0, sizeof (*a));
384       a->app_index = ecm->app_index;
385       a->api_context = -1 - api_context;
386       clib_memcpy (&a->sep_ext, &sep, sizeof (sep));
387
388       DBG ("QUIC opening stream %d", stream_n);
389       if ((rv = vnet_connect (a)))
390         {
391           clib_error ("Stream session %d opening failed: %d", stream_n, rv);
392           return -1;
393         }
394       DBG ("QUIC stream %d connected", stream_n);
395     }
396   vec_add1 (ecm->quic_session_index_by_thread[thread_index],
397             session_handle (s));
398   vec_free (a);
399   return 0;
400 }
401
402 static int
403 quic_echo_clients_session_connected_callback (u32 app_index, u32 api_context,
404                                               session_t * s, u8 is_fail)
405 {
406   echo_client_main_t *ecm = &echo_client_main;
407   eclient_session_t *session;
408   u32 session_index;
409   u8 thread_index;
410
411   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_STARTING))
412     return -1;
413
414   if (is_fail)
415     {
416       clib_warning ("connection %d failed!", api_context);
417       ecm->run_test = ECHO_CLIENTS_EXITING;
418       signal_evt_to_cli (-1);
419       return 0;
420     }
421
422   if (s->listener_handle == SESSION_INVALID_HANDLE)
423     return quic_echo_clients_qsession_connected_callback (app_index,
424                                                           api_context, s,
425                                                           is_fail);
426   DBG ("STREAM Connection callback %d", api_context);
427
428   thread_index = s->thread_index;
429   ASSERT (thread_index == vlib_get_thread_index ()
430           || session_transport_service_type (s) == TRANSPORT_SERVICE_CL);
431
432   if (!ecm->vpp_event_queue[thread_index])
433     ecm->vpp_event_queue[thread_index] =
434       session_main_get_vpp_event_queue (thread_index);
435
436   /*
437    * Setup session
438    */
439   clib_spinlock_lock_if_init (&ecm->sessions_lock);
440   pool_get (ecm->sessions, session);
441   clib_spinlock_unlock_if_init (&ecm->sessions_lock);
442
443   clib_memset (session, 0, sizeof (*session));
444   session_index = session - ecm->sessions;
445   session->bytes_to_send = ecm->bytes_to_send;
446   session->bytes_to_receive = ecm->no_return ? 0ULL : ecm->bytes_to_send;
447   session->data.rx_fifo = s->rx_fifo;
448   session->data.rx_fifo->client_session_index = session_index;
449   session->data.tx_fifo = s->tx_fifo;
450   session->data.tx_fifo->client_session_index = session_index;
451   session->data.vpp_evt_q = ecm->vpp_event_queue[thread_index];
452   session->vpp_session_handle = session_handle (s);
453
454   if (ecm->is_dgram)
455     {
456       transport_connection_t *tc;
457       tc = session_get_transport (s);
458       clib_memcpy_fast (&session->data.transport, tc,
459                         sizeof (session->data.transport));
460       session->data.is_dgram = 1;
461     }
462
463   vec_add1 (ecm->connection_index_by_thread[thread_index], session_index);
464   clib_atomic_fetch_add (&ecm->ready_connections, 1);
465   if (ecm->ready_connections == ecm->expected_connections)
466     {
467       ecm->run_test = ECHO_CLIENTS_RUNNING;
468       /* Signal the CLI process that the action is starting... */
469       signal_evt_to_cli (1);
470     }
471
472   return 0;
473 }
474
475 static int
476 echo_clients_session_connected_callback (u32 app_index, u32 api_context,
477                                          session_t * s, u8 is_fail)
478 {
479   echo_client_main_t *ecm = &echo_client_main;
480   eclient_session_t *session;
481   u32 session_index;
482   u8 thread_index;
483
484   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_STARTING))
485     return -1;
486
487   if (is_fail)
488     {
489       clib_warning ("connection %d failed!", api_context);
490       ecm->run_test = ECHO_CLIENTS_EXITING;
491       signal_evt_to_cli (-1);
492       return 0;
493     }
494
495   thread_index = s->thread_index;
496   ASSERT (thread_index == vlib_get_thread_index ()
497           || session_transport_service_type (s) == TRANSPORT_SERVICE_CL);
498
499   if (!ecm->vpp_event_queue[thread_index])
500     ecm->vpp_event_queue[thread_index] =
501       session_main_get_vpp_event_queue (thread_index);
502
503   /*
504    * Setup session
505    */
506   clib_spinlock_lock_if_init (&ecm->sessions_lock);
507   pool_get (ecm->sessions, session);
508   clib_spinlock_unlock_if_init (&ecm->sessions_lock);
509
510   clib_memset (session, 0, sizeof (*session));
511   session_index = session - ecm->sessions;
512   session->bytes_to_send = ecm->bytes_to_send;
513   session->bytes_to_receive = ecm->no_return ? 0ULL : ecm->bytes_to_send;
514   session->data.rx_fifo = s->rx_fifo;
515   session->data.rx_fifo->client_session_index = session_index;
516   session->data.tx_fifo = s->tx_fifo;
517   session->data.tx_fifo->client_session_index = session_index;
518   session->data.vpp_evt_q = ecm->vpp_event_queue[thread_index];
519   session->vpp_session_handle = session_handle (s);
520
521   if (ecm->is_dgram)
522     {
523       transport_connection_t *tc;
524       tc = session_get_transport (s);
525       clib_memcpy_fast (&session->data.transport, tc,
526                         sizeof (session->data.transport));
527       session->data.is_dgram = 1;
528     }
529
530   vec_add1 (ecm->connection_index_by_thread[thread_index], session_index);
531   clib_atomic_fetch_add (&ecm->ready_connections, 1);
532   if (ecm->ready_connections == ecm->expected_connections)
533     {
534       ecm->run_test = ECHO_CLIENTS_RUNNING;
535       /* Signal the CLI process that the action is starting... */
536       signal_evt_to_cli (1);
537     }
538
539   return 0;
540 }
541
542 static void
543 echo_clients_session_reset_callback (session_t * s)
544 {
545   echo_client_main_t *ecm = &echo_client_main;
546   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
547
548   if (s->session_state == SESSION_STATE_READY)
549     clib_warning ("Reset active connection %U", format_session, s, 2);
550
551   a->handle = session_handle (s);
552   a->app_index = ecm->app_index;
553   vnet_disconnect_session (a);
554   return;
555 }
556
557 static int
558 echo_clients_session_create_callback (session_t * s)
559 {
560   return 0;
561 }
562
563 static void
564 echo_clients_session_disconnect_callback (session_t * s)
565 {
566   echo_client_main_t *ecm = &echo_client_main;
567   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
568   a->handle = session_handle (s);
569   a->app_index = ecm->app_index;
570   vnet_disconnect_session (a);
571   return;
572 }
573
574 void
575 echo_clients_session_disconnect (session_t * s)
576 {
577   echo_client_main_t *ecm = &echo_client_main;
578   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
579   a->handle = session_handle (s);
580   a->app_index = ecm->app_index;
581   vnet_disconnect_session (a);
582 }
583
584 static int
585 echo_clients_rx_callback (session_t * s)
586 {
587   echo_client_main_t *ecm = &echo_client_main;
588   eclient_session_t *sp;
589
590   if (PREDICT_FALSE (ecm->run_test != ECHO_CLIENTS_RUNNING))
591     {
592       echo_clients_session_disconnect (s);
593       return -1;
594     }
595
596   sp = pool_elt_at_index (ecm->sessions, s->rx_fifo->client_session_index);
597   receive_data_chunk (ecm, sp);
598
599   if (svm_fifo_max_dequeue_cons (s->rx_fifo))
600     {
601       if (svm_fifo_set_event (s->rx_fifo))
602         session_send_io_evt_to_thread (s->rx_fifo, SESSION_IO_EVT_BUILTIN_RX);
603     }
604   return 0;
605 }
606
607 int
608 echo_client_add_segment_callback (u32 client_index, u64 segment_handle)
609 {
610   /* New heaps may be added */
611   return 0;
612 }
613
614 /* *INDENT-OFF* */
615 static session_cb_vft_t echo_clients = {
616   .session_reset_callback = echo_clients_session_reset_callback,
617   .session_connected_callback = echo_clients_session_connected_callback,
618   .session_accept_callback = echo_clients_session_create_callback,
619   .session_disconnect_callback = echo_clients_session_disconnect_callback,
620   .builtin_app_rx_callback = echo_clients_rx_callback,
621   .add_segment_callback = echo_client_add_segment_callback
622 };
623 /* *INDENT-ON* */
624
625 static clib_error_t *
626 echo_clients_attach (u8 * appns_id, u64 appns_flags, u64 appns_secret)
627 {
628   u32 prealloc_fifos, segment_size = 256 << 20;
629   echo_client_main_t *ecm = &echo_client_main;
630   vnet_app_attach_args_t _a, *a = &_a;
631   u64 options[16];
632   int rv;
633
634   clib_memset (a, 0, sizeof (*a));
635   clib_memset (options, 0, sizeof (options));
636
637   a->api_client_index = ecm->my_client_index;
638   if (ecm->transport_proto == TRANSPORT_PROTO_QUIC)
639     echo_clients.session_connected_callback =
640       quic_echo_clients_session_connected_callback;
641   a->session_cb_vft = &echo_clients;
642
643   prealloc_fifos = ecm->prealloc_fifos ? ecm->expected_connections : 1;
644
645   if (ecm->private_segment_size)
646     segment_size = ecm->private_segment_size;
647
648   options[APP_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
649   options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
650   options[APP_OPTIONS_ADD_SEGMENT_SIZE] = segment_size;
651   options[APP_OPTIONS_RX_FIFO_SIZE] = ecm->fifo_size;
652   options[APP_OPTIONS_TX_FIFO_SIZE] = ecm->fifo_size;
653   options[APP_OPTIONS_PRIVATE_SEGMENT_COUNT] = ecm->private_segment_count;
654   options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = prealloc_fifos;
655   options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
656   options[APP_OPTIONS_TLS_ENGINE] = ecm->tls_engine;
657   if (appns_id)
658     {
659       options[APP_OPTIONS_FLAGS] |= appns_flags;
660       options[APP_OPTIONS_NAMESPACE_SECRET] = appns_secret;
661     }
662   a->options = options;
663   a->namespace_id = appns_id;
664
665   if ((rv = vnet_application_attach (a)))
666     return clib_error_return (0, "attach returned %d", rv);
667
668   ecm->app_index = a->app_index;
669   return 0;
670 }
671
672 static int
673 echo_clients_detach ()
674 {
675   echo_client_main_t *ecm = &echo_client_main;
676   vnet_app_detach_args_t _da, *da = &_da;
677   int rv;
678
679   da->app_index = ecm->app_index;
680   da->api_client_index = ~0;
681   rv = vnet_application_detach (da);
682   ecm->test_client_attached = 0;
683   ecm->app_index = ~0;
684   return rv;
685 }
686
687 static void *
688 echo_client_thread_fn (void *arg)
689 {
690   return 0;
691 }
692
693 /** Start a transmit thread */
694 int
695 echo_clients_start_tx_pthread (echo_client_main_t * ecm)
696 {
697   if (ecm->client_thread_handle == 0)
698     {
699       int rv = pthread_create (&ecm->client_thread_handle,
700                                NULL /*attr */ ,
701                                echo_client_thread_fn, 0);
702       if (rv)
703         {
704           ecm->client_thread_handle = 0;
705           return -1;
706         }
707     }
708   return 0;
709 }
710
711 clib_error_t *
712 echo_clients_connect (vlib_main_t * vm, u32 n_clients)
713 {
714   echo_client_main_t *ecm = &echo_client_main;
715   vnet_connect_args_t _a, *a = &_a;
716   int i, rv;
717
718   clib_memset (a, 0, sizeof (*a));
719
720   for (i = 0; i < n_clients; i++)
721     {
722       a->uri = (char *) ecm->connect_uri;
723       a->api_context = i;
724       a->app_index = ecm->app_index;
725       if ((rv = vnet_connect_uri (a)))
726         return clib_error_return (0, "connect returned: %d", rv);
727
728       /* Crude pacing for call setups  */
729       if ((i % 16) == 0)
730         vlib_process_suspend (vm, 100e-6);
731       ASSERT (i + 1 >= ecm->ready_connections);
732       while (i + 1 - ecm->ready_connections > 128)
733         vlib_process_suspend (vm, 1e-3);
734     }
735   return 0;
736 }
737
738 #define ec_cli_output(_fmt, _args...)                   \
739   if (!ecm->no_output)                                  \
740     vlib_cli_output(vm, _fmt, ##_args)
741
742 static clib_error_t *
743 echo_clients_command_fn (vlib_main_t * vm,
744                          unformat_input_t * input, vlib_cli_command_t * cmd)
745 {
746   echo_client_main_t *ecm = &echo_client_main;
747   vlib_thread_main_t *thread_main = vlib_get_thread_main ();
748   u64 tmp, total_bytes, appns_flags = 0, appns_secret = 0;
749   f64 test_timeout = 20.0, syn_timeout = 20.0, delta;
750   char *default_uri = "tcp://6.0.1.1/1234";
751   uword *event_data = 0, event_type;
752   f64 time_before_connects;
753   u32 n_clients = 1;
754   int preallocate_sessions = 0;
755   char *transfer_type;
756   clib_error_t *error = 0;
757   u8 *appns_id = 0;
758   int i;
759   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
760   int rv;
761
762   ecm->quic_streams = 1;
763   ecm->bytes_to_send = 8192;
764   ecm->no_return = 0;
765   ecm->fifo_size = 64 << 10;
766   ecm->connections_per_batch = 1000;
767   ecm->private_segment_count = 0;
768   ecm->private_segment_size = 0;
769   ecm->no_output = 0;
770   ecm->test_bytes = 0;
771   ecm->test_failed = 0;
772   ecm->vlib_main = vm;
773   ecm->tls_engine = TLS_ENGINE_OPENSSL;
774   ecm->no_copy = 0;
775   ecm->run_test = ECHO_CLIENTS_STARTING;
776
777   if (thread_main->n_vlib_mains > 1)
778     clib_spinlock_init (&ecm->sessions_lock);
779   vec_free (ecm->connect_uri);
780
781   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
782     {
783       if (unformat (input, "uri %s", &ecm->connect_uri))
784         ;
785       else if (unformat (input, "nclients %d", &n_clients))
786         ;
787       else if (unformat (input, "quic-streams %d", &ecm->quic_streams))
788         ;
789       else if (unformat (input, "mbytes %lld", &tmp))
790         ecm->bytes_to_send = tmp << 20;
791       else if (unformat (input, "gbytes %lld", &tmp))
792         ecm->bytes_to_send = tmp << 30;
793       else if (unformat (input, "bytes %lld", &ecm->bytes_to_send))
794         ;
795       else if (unformat (input, "test-timeout %f", &test_timeout))
796         ;
797       else if (unformat (input, "syn-timeout %f", &syn_timeout))
798         ;
799       else if (unformat (input, "no-return"))
800         ecm->no_return = 1;
801       else if (unformat (input, "fifo-size %d", &ecm->fifo_size))
802         ecm->fifo_size <<= 10;
803       else if (unformat (input, "private-segment-count %d",
804                          &ecm->private_segment_count))
805         ;
806       else if (unformat (input, "private-segment-size %U",
807                          unformat_memory_size, &tmp))
808         {
809           if (tmp >= 0x100000000ULL)
810             return clib_error_return
811               (0, "private segment size %lld (%llu) too large", tmp, tmp);
812           ecm->private_segment_size = tmp;
813         }
814       else if (unformat (input, "preallocate-fifos"))
815         ecm->prealloc_fifos = 1;
816       else if (unformat (input, "preallocate-sessions"))
817         preallocate_sessions = 1;
818       else
819         if (unformat (input, "client-batch %d", &ecm->connections_per_batch))
820         ;
821       else if (unformat (input, "appns %_%v%_", &appns_id))
822         ;
823       else if (unformat (input, "all-scope"))
824         appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE
825                         | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE);
826       else if (unformat (input, "local-scope"))
827         appns_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
828       else if (unformat (input, "global-scope"))
829         appns_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
830       else if (unformat (input, "secret %lu", &appns_secret))
831         ;
832       else if (unformat (input, "no-output"))
833         ecm->no_output = 1;
834       else if (unformat (input, "test-bytes"))
835         ecm->test_bytes = 1;
836       else if (unformat (input, "tls-engine %d", &ecm->tls_engine))
837         ;
838       else
839         return clib_error_return (0, "failed: unknown input `%U'",
840                                   format_unformat_error, input);
841     }
842
843   /* Store cli process node index for signalling */
844   ecm->cli_node_index =
845     vlib_get_current_process (vm)->node_runtime.node_index;
846
847   if (ecm->is_init == 0)
848     {
849       if (echo_clients_init (vm))
850         return clib_error_return (0, "failed init");
851     }
852
853
854   ecm->ready_connections = 0;
855   ecm->expected_connections = n_clients * ecm->quic_streams;
856   ecm->rx_total = 0;
857   ecm->tx_total = 0;
858
859   if (!ecm->connect_uri)
860     {
861       clib_warning ("No uri provided. Using default: %s", default_uri);
862       ecm->connect_uri = format (0, "%s%c", default_uri, 0);
863     }
864
865   if ((rv = parse_uri ((char *) ecm->connect_uri, &sep)))
866     return clib_error_return (0, "Uri parse error: %d", rv);
867   ecm->transport_proto = sep.transport_proto;
868   ecm->is_dgram = (sep.transport_proto == TRANSPORT_PROTO_UDP);
869
870 #if ECHO_CLIENT_PTHREAD
871   echo_clients_start_tx_pthread ();
872 #endif
873
874   vlib_worker_thread_barrier_sync (vm);
875   vnet_session_enable_disable (vm, 1 /* turn on session and transports */ );
876   vlib_worker_thread_barrier_release (vm);
877
878   if (ecm->test_client_attached == 0)
879     {
880       if ((error = echo_clients_attach (appns_id, appns_flags, appns_secret)))
881         {
882           vec_free (appns_id);
883           clib_error_report (error);
884           return error;
885         }
886       vec_free (appns_id);
887     }
888   ecm->test_client_attached = 1;
889
890   /* Turn on the builtin client input nodes */
891   for (i = 0; i < thread_main->n_vlib_mains; i++)
892     vlib_node_set_state (vlib_mains[i], echo_clients_node.index,
893                          VLIB_NODE_STATE_POLLING);
894
895   if (preallocate_sessions)
896     pool_init_fixed (ecm->sessions, 1.1 * n_clients);
897
898   /* Fire off connect requests */
899   time_before_connects = vlib_time_now (vm);
900   if ((error = echo_clients_connect (vm, n_clients)))
901     goto cleanup;
902
903   /* Park until the sessions come up, or ten seconds elapse... */
904   vlib_process_wait_for_event_or_clock (vm, syn_timeout);
905   event_type = vlib_process_get_events (vm, &event_data);
906   switch (event_type)
907     {
908     case ~0:
909       ec_cli_output ("Timeout with only %d sessions active...",
910                      ecm->ready_connections);
911       error = clib_error_return (0, "failed: syn timeout with %d sessions",
912                                  ecm->ready_connections);
913       goto cleanup;
914
915     case 1:
916       delta = vlib_time_now (vm) - time_before_connects;
917       if (delta != 0.0)
918         ec_cli_output ("%d three-way handshakes in %.2f seconds %.2f/s",
919                        n_clients, delta, ((f64) n_clients) / delta);
920
921       ecm->test_start_time = vlib_time_now (ecm->vlib_main);
922       ec_cli_output ("Test started at %.6f", ecm->test_start_time);
923       break;
924
925     default:
926       ec_cli_output ("unexpected event(1): %d", event_type);
927       error = clib_error_return (0, "failed: unexpected event(1): %d",
928                                  event_type);
929       goto cleanup;
930     }
931
932   /* Now wait for the sessions to finish... */
933   vlib_process_wait_for_event_or_clock (vm, test_timeout);
934   event_type = vlib_process_get_events (vm, &event_data);
935   switch (event_type)
936     {
937     case ~0:
938       ec_cli_output ("Timeout with %d sessions still active...",
939                      ecm->ready_connections);
940       error = clib_error_return (0, "failed: timeout with %d sessions",
941                                  ecm->ready_connections);
942       goto cleanup;
943
944     case 2:
945       ecm->test_end_time = vlib_time_now (vm);
946       ec_cli_output ("Test finished at %.6f", ecm->test_end_time);
947       break;
948
949     default:
950       ec_cli_output ("unexpected event(2): %d", event_type);
951       error = clib_error_return (0, "failed: unexpected event(2): %d",
952                                  event_type);
953       goto cleanup;
954     }
955
956   delta = ecm->test_end_time - ecm->test_start_time;
957   if (delta != 0.0)
958     {
959       total_bytes = (ecm->no_return ? ecm->tx_total : ecm->rx_total);
960       transfer_type = ecm->no_return ? "half-duplex" : "full-duplex";
961       ec_cli_output ("%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds",
962                      total_bytes, total_bytes / (1ULL << 20),
963                      total_bytes / (1ULL << 30), delta);
964       ec_cli_output ("%.2f bytes/second %s", ((f64) total_bytes) / (delta),
965                      transfer_type);
966       ec_cli_output ("%.4f gbit/second %s",
967                      (((f64) total_bytes * 8.0) / delta / 1e9),
968                      transfer_type);
969     }
970   else
971     {
972       ec_cli_output ("zero delta-t?");
973       error = clib_error_return (0, "failed: zero delta-t");
974       goto cleanup;
975     }
976
977   if (ecm->test_bytes && ecm->test_failed)
978     error = clib_error_return (0, "failed: test bytes");
979
980 cleanup:
981   ecm->run_test = ECHO_CLIENTS_EXITING;
982   vlib_process_wait_for_event_or_clock (vm, 10e-3);
983   for (i = 0; i < vec_len (ecm->connection_index_by_thread); i++)
984     {
985       vec_reset_length (ecm->connection_index_by_thread[i]);
986       vec_reset_length (ecm->connections_this_batch_by_thread[i]);
987       vec_reset_length (ecm->quic_session_index_by_thread[i]);
988     }
989
990   pool_free (ecm->sessions);
991
992   /* Detach the application, so we can use different fifo sizes next time */
993   if (ecm->test_client_attached)
994     {
995       if (echo_clients_detach ())
996         {
997           error = clib_error_return (0, "failed: app detach");
998           ec_cli_output ("WARNING: app detach failed...");
999         }
1000     }
1001   if (error)
1002     ec_cli_output ("test failed");
1003   vec_free (ecm->connect_uri);
1004   return error;
1005 }
1006
1007 /* *INDENT-OFF* */
1008 VLIB_CLI_COMMAND (echo_clients_command, static) =
1009 {
1010   .path = "test echo clients",
1011   .short_help = "test echo clients [nclients %d][[m|g]bytes <bytes>]"
1012       "[test-timeout <time>][syn-timeout <time>][no-return][fifo-size <size>]"
1013       "[private-segment-count <count>][private-segment-size <bytes>[m|g]]"
1014       "[preallocate-fifos][preallocate-sessions][client-batch <batch-size>]"
1015       "[uri <tcp://ip/port>][test-bytes][no-output]",
1016   .function = echo_clients_command_fn,
1017   .is_mp_safe = 1,
1018 };
1019 /* *INDENT-ON* */
1020
1021 clib_error_t *
1022 echo_clients_main_init (vlib_main_t * vm)
1023 {
1024   echo_client_main_t *ecm = &echo_client_main;
1025   ecm->is_init = 0;
1026   return 0;
1027 }
1028
1029 VLIB_INIT_FUNCTION (echo_clients_main_init);
1030
1031 /*
1032  * fd.io coding-style-patch-verification: ON
1033  *
1034  * Local Variables:
1035  * eval: (c-set-style "gnu")
1036  * End:
1037  */