aaefa7ebb9a8dd248ea278d011c1097212b199e5
[vpp.git] / src / vnet / tcp / builtin_client.c
1 /*
2  * builtin_client.c - vpp built-in tcp client/connect code
3  *
4  * Copyright (c) 2017 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 <vnet/plugin/plugin.h>
20 #include <vnet/tcp/builtin_client.h>
21
22 #include <vlibapi/api.h>
23 #include <vlibmemory/api.h>
24 #include <vlibsocket/api.h>
25 #include <vpp/app/version.h>
26
27 /* define message IDs */
28 #include <vpp/api/vpe_msg_enum.h>
29
30 /* define message structures */
31 #define vl_typedefs
32 #include <vpp/api/vpe_all_api_h.h>
33 #undef vl_typedefs
34
35 /* define generated endian-swappers */
36 #define vl_endianfun
37 #include <vpp/api/vpe_all_api_h.h>
38 #undef vl_endianfun
39
40 /* instantiate all the print functions we know about */
41 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
42 #define vl_printfun
43 #include <vpp/api/vpe_all_api_h.h>
44 #undef vl_printfun
45
46 #define TCP_BUILTIN_CLIENT_DBG (1)
47 #define TCP_BUILTIN_CLIENT_VPP_THREAD (0)
48 #define TCP_BUILTIN_CLIENT_PTHREAD (!TCP_BUILTIN_CLIENT_VPP_THREAD)
49
50 static void
51 send_test_chunk (tclient_main_t * tm, session_t * s)
52 {
53   u8 *test_data = tm->connect_test_data;
54   int test_buf_offset;
55   u32 bytes_this_chunk;
56   session_fifo_event_t evt;
57   static int serial_number = 0;
58   int rv;
59
60   ASSERT (vec_len (test_data) > 0);
61
62   test_buf_offset = s->bytes_sent % vec_len (test_data);
63   bytes_this_chunk = vec_len (test_data) - test_buf_offset;
64
65   bytes_this_chunk = bytes_this_chunk < s->bytes_to_send
66     ? bytes_this_chunk : s->bytes_to_send;
67
68   rv = svm_fifo_enqueue_nowait (s->server_tx_fifo, bytes_this_chunk,
69                                 test_data + test_buf_offset);
70
71   /* If we managed to enqueue data... */
72   if (rv > 0)
73     {
74       /* Account for it... */
75       s->bytes_to_send -= rv;
76       s->bytes_sent += rv;
77
78       if (TCP_BUILTIN_CLIENT_DBG)
79         {
80           /* *INDENT-OFF* */
81           ELOG_TYPE_DECLARE (e) =
82             {
83               .format = "tx-enq: xfer %d bytes, sent %u remain %u",
84               .format_args = "i4i4i4",
85             };
86           /* *INDENT-ON* */
87           struct
88           {
89             u32 data[3];
90           } *ed;
91           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
92           ed->data[0] = rv;
93           ed->data[1] = s->bytes_sent;
94           ed->data[2] = s->bytes_to_send;
95         }
96
97       /* Poke the TCP state machine */
98       if (svm_fifo_set_event (s->server_tx_fifo))
99         {
100           /* Fabricate TX event, send to vpp */
101           evt.fifo = s->server_tx_fifo;
102           evt.event_type = FIFO_EVENT_APP_TX;
103           evt.event_id = serial_number++;
104
105           unix_shared_memory_queue_add (tm->vpp_event_queue, (u8 *) & evt,
106                                         0 /* do wait for mutex */ );
107         }
108     }
109 }
110
111 static void
112 receive_test_chunk (tclient_main_t * tm, session_t * s)
113 {
114   svm_fifo_t *rx_fifo = s->server_rx_fifo;
115   int n_read, test_bytes = 0;
116
117   /* Allow enqueuing of new event */
118   // svm_fifo_unset_event (rx_fifo);
119
120   n_read = svm_fifo_dequeue_nowait (rx_fifo, vec_len (tm->rx_buf),
121                                     tm->rx_buf);
122   if (n_read > 0)
123     {
124       if (TCP_BUILTIN_CLIENT_DBG)
125         {
126           /* *INDENT-OFF* */
127           ELOG_TYPE_DECLARE (e) =
128             {
129               .format = "rx-deq: %d bytes",
130               .format_args = "i4",
131             };
132           /* *INDENT-ON* */
133           struct
134           {
135             u32 data[1];
136           } *ed;
137           ed = ELOG_DATA (&vlib_global_main.elog_main, e);
138           ed->data[0] = n_read;
139         }
140
141       if (test_bytes)
142         {
143           int i;
144           for (i = 0; i < n_read; i++)
145             {
146               if (tm->rx_buf[i] != ((s->bytes_received + i) & 0xff))
147                 {
148                   clib_warning ("read %d error at byte %lld, 0x%x not 0x%x",
149                                 n_read, s->bytes_received + i, tm->rx_buf[i],
150                                 ((s->bytes_received + i) & 0xff));
151                 }
152             }
153         }
154       s->bytes_to_receive -= n_read;
155       s->bytes_received += n_read;
156     }
157 }
158
159 #if TCP_BUILTIN_CLIENT_VPP_THREAD
160 #define THREAD_PROTOTYPE static void
161 #else
162 #define THREAD_PROTOTYPE static void *
163 #endif
164
165 THREAD_PROTOTYPE
166 tclient_thread_fn (void *arg)
167 {
168   tclient_main_t *tm = &tclient_main;
169   vl_api_disconnect_session_t *dmp;
170   session_t *sp;
171   struct timespec ts, tsrem;
172   int i;
173   int try_tx, try_rx;
174   u32 *session_indices = 0;
175   clib_time_t ttime;
176   f64 before, after;
177   u64 rx_total;
178
179   clib_time_init (&ttime);
180
181   /* stats thread wants no signals. */
182   {
183     sigset_t s;
184     sigfillset (&s);
185     pthread_sigmask (SIG_SETMASK, &s, 0);
186   }
187
188   clib_per_cpu_mheaps[vlib_get_thread_index ()] = clib_per_cpu_mheaps[0];
189
190   vec_validate (session_indices, 0);
191   vec_reset_length (session_indices);
192
193   while (1)
194     {
195       /* Wait until we're told to get busy */
196       while (tm->run_test == 0
197              || (tm->ready_connections != tm->expected_connections))
198         {
199           ts.tv_sec = 0;
200           ts.tv_nsec = 100000000;
201           while (nanosleep (&ts, &tsrem) < 0)
202             ts = tsrem;
203         }
204       tm->run_test = 0;
205       rx_total = 0;
206
207       clib_warning ("Start test...");
208
209       before = clib_time_now (&ttime);
210
211       do
212         {
213           do
214             {
215               try_tx = try_rx = 0;
216
217               /* *INDENT-OFF* */
218               pool_foreach (sp, tm->sessions,
219               ({
220                 if (sp->bytes_to_send > 0)
221                   {
222                     send_test_chunk (tm, sp);
223                     try_tx = 1;
224                   }
225               }));
226               pool_foreach (sp, tm->sessions,
227               ({
228                 if (sp->bytes_to_receive > 0)
229                   {
230                     receive_test_chunk (tm, sp);
231                     try_rx = 1;
232                   }
233                 else
234                   {
235                     /* Session is complete */
236                     vec_add1 (session_indices, sp - tm->sessions);
237                   }
238               }));
239               /* Terminate any completed sessions */
240               if (PREDICT_FALSE (_vec_len(session_indices) != 0))
241                 {
242                   for (i = 0; i < _vec_len (session_indices); i++)
243                     {
244                       sp = pool_elt_at_index (tm->sessions, session_indices[i]);
245                       rx_total += sp->bytes_received;
246                       dmp = vl_msg_api_alloc_as_if_client (sizeof (*dmp));
247                       memset (dmp, 0, sizeof (*dmp));
248                       dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
249                       dmp->client_index = tm->my_client_index;
250                       dmp->handle = sp->vpp_session_handle;
251                       vl_msg_api_send_shmem (tm->vl_input_queue, (u8 *) & dmp);
252                       pool_put (tm->sessions, sp);
253                     }
254                   _vec_len(session_indices) = 0;
255                 }
256               /* *INDENT-ON* */
257             }
258           while (try_tx || try_rx);
259         }
260       while (0);
261       after = clib_time_now (&ttime);
262
263       clib_warning ("Test complete %lld bytes in %.2f secs",
264                     rx_total, (after - before));
265       if ((after - before) != 0.0)
266         {
267           clib_warning ("%.2f bytes/second full-duplex",
268                         ((f64) rx_total) / (after - before));
269           clib_warning ("%.4f gbit/second full-duplex",
270                         (((f64) rx_total * 8.0) / (after - before)) / 1e9);
271         }
272
273       if (pool_elts (tm->sessions))
274         clib_warning ("BUG: %d active sessions remain...",
275                       pool_elts (tm->sessions));
276     }
277   while (0);
278   /* NOTREACHED */
279 #if TCP_BUILTIN_CLIENT_PTHREAD
280   return 0;
281 #endif
282 }
283
284 /* So we don't get "no handler for... " msgs */
285 static void
286 vl_api_memclnt_create_reply_t_handler (vl_api_memclnt_create_reply_t * mp)
287 {
288   vlib_main_t *vm = vlib_get_main ();
289   tclient_main_t *tm = &tclient_main;
290   tm->my_client_index = mp->index;
291   vlib_process_signal_event (vm, tm->node_index, 1 /* evt */ ,
292                              0 /* data */ );
293 }
294
295 static void
296 vl_api_connect_uri_reply_t_handler (vl_api_connect_uri_reply_t * mp)
297 {
298   tclient_main_t *tm = &tclient_main;
299   session_t *session;
300   u32 session_index;
301   i32 retval = /* clib_net_to_host_u32 ( */ mp->retval /*) */ ;
302
303   if (retval < 0)
304     {
305       clib_warning ("connection failed: retval %d", retval);
306       return;
307     }
308
309   tm->our_event_queue =
310     uword_to_pointer (mp->vpp_event_queue_address,
311                       unix_shared_memory_queue_t *);
312   tm->vpp_event_queue =
313     uword_to_pointer (mp->vpp_event_queue_address,
314                       unix_shared_memory_queue_t *);
315
316   /*
317    * Setup session
318    */
319   pool_get (tm->sessions, session);
320   memset (session, 0, sizeof (*session));
321   session_index = session - tm->sessions;
322   session->bytes_to_receive = session->bytes_to_send = tm->bytes_to_send;
323
324   session->server_rx_fifo =
325     uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
326   session->server_rx_fifo->client_session_index = session_index;
327   session->server_tx_fifo =
328     uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
329   session->server_tx_fifo->client_session_index = session_index;
330   session->vpp_session_handle = mp->handle;
331
332   /* Add it to the session lookup table */
333   hash_set (tm->session_index_by_vpp_handles, mp->handle, session_index);
334
335   tm->ready_connections++;
336 }
337
338 static int
339 create_api_loopback (tclient_main_t * tm)
340 {
341   vlib_main_t *vm = vlib_get_main ();
342   vl_api_memclnt_create_t _m, *mp = &_m;
343   extern void vl_api_memclnt_create_t_handler (vl_api_memclnt_create_t *);
344   api_main_t *am = &api_main;
345   vl_shmem_hdr_t *shmem_hdr;
346   uword *event_data = 0, event_type;
347   int resolved = 0;
348
349   /*
350    * Create a "loopback" API client connection
351    * Don't do things like this unless you know what you're doing...
352    */
353
354   shmem_hdr = am->shmem_hdr;
355   tm->vl_input_queue = shmem_hdr->vl_input_queue;
356   memset (mp, 0, sizeof (*mp));
357   mp->_vl_msg_id = VL_API_MEMCLNT_CREATE;
358   mp->context = 0xFEEDFACE;
359   mp->input_queue = pointer_to_uword (tm->vl_input_queue);
360   strncpy ((char *) mp->name, "tcp_tester", sizeof (mp->name) - 1);
361
362   vl_api_memclnt_create_t_handler (mp);
363
364   /* Wait for reply */
365   tm->node_index = vlib_get_current_process (vm)->node_runtime.node_index;
366   vlib_process_wait_for_event_or_clock (vm, 1.0);
367   event_type = vlib_process_get_events (vm, &event_data);
368   switch (event_type)
369     {
370     case 1:
371       resolved = 1;
372       break;
373     case ~0:
374       /* timed out */
375       break;
376     default:
377       clib_warning ("unknown event_type %d", event_type);
378     }
379   if (!resolved)
380     return -1;
381   return 0;
382 }
383
384 #define foreach_tclient_static_api_msg          \
385 _(MEMCLNT_CREATE_REPLY, memclnt_create_reply)   \
386 _(CONNECT_URI_REPLY, connect_uri_reply)
387
388 static clib_error_t *
389 tclient_api_hookup (vlib_main_t * vm)
390 {
391   vl_msg_api_msg_config_t _c, *c = &_c;
392
393   /* Hook up client-side static APIs to our handlers */
394 #define _(N,n) do {                                             \
395     c->id = VL_API_##N;                                         \
396     c->name = #n;                                               \
397     c->handler = vl_api_##n##_t_handler;                        \
398     c->cleanup = vl_noop_handler;                               \
399     c->endian = vl_api_##n##_t_endian;                          \
400     c->print = vl_api_##n##_t_print;                            \
401     c->size = sizeof(vl_api_##n##_t);                           \
402     c->traced = 1; /* trace, so these msgs print */             \
403     c->replay = 0; /* don't replay client create/delete msgs */ \
404     c->message_bounce = 0; /* don't bounce this message */      \
405     vl_msg_api_config(c);} while (0);
406
407   foreach_tclient_static_api_msg;
408 #undef _
409
410   return 0;
411 }
412
413 static int
414 tcp_test_clients_init (vlib_main_t * vm)
415 {
416   tclient_main_t *tm = &tclient_main;
417   int i;
418
419   tclient_api_hookup (vm);
420   if (create_api_loopback (tm))
421     return -1;
422
423   /* Init test data */
424   vec_validate (tm->connect_test_data, 64 * 1024 - 1);
425   for (i = 0; i < vec_len (tm->connect_test_data); i++)
426     tm->connect_test_data[i] = i & 0xff;
427
428   tm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
429   vec_validate (tm->rx_buf, vec_len (tm->connect_test_data) - 1);
430
431   tm->is_init = 1;
432
433   return 0;
434 }
435
436 static void
437 builtin_session_reset_callback (stream_session_t * s)
438 {
439   return;
440 }
441
442 static int
443 builtin_session_create_callback (stream_session_t * s)
444 {
445   return 0;
446 }
447
448 static void
449 builtin_session_disconnect_callback (stream_session_t * s)
450 {
451   return;
452 }
453
454 static int
455 builtin_server_rx_callback (stream_session_t * s)
456 {
457   return 0;
458 }
459
460 /* *INDENT-OFF* */
461 static session_cb_vft_t builtin_clients =
462   {
463     .session_reset_callback = builtin_session_reset_callback,
464     .session_connected_callback = send_session_connected_callback,
465     .session_accept_callback = builtin_session_create_callback,
466     .session_disconnect_callback = builtin_session_disconnect_callback,
467     .builtin_server_rx_callback = builtin_server_rx_callback
468   };
469 /* *INDENT-ON* */
470
471 static int
472 attach_builtin_test_clients ()
473 {
474   tclient_main_t *tm = &tclient_main;
475   vnet_app_attach_args_t _a, *a = &_a;
476   u8 segment_name[128];
477   u32 segment_name_length;
478   u64 options[16];
479
480   segment_name_length = ARRAY_LEN (segment_name);
481
482   memset (a, 0, sizeof (*a));
483   memset (options, 0, sizeof (options));
484
485   a->api_client_index = tm->my_client_index;
486   a->segment_name = segment_name;
487   a->segment_name_length = segment_name_length;
488   a->session_cb_vft = &builtin_clients;
489
490   options[SESSION_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
491   options[SESSION_OPTIONS_SEGMENT_SIZE] = (2 << 30);    /*$$$$ config / arg */
492   options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_BUILTIN_APP;
493
494   a->options = options;
495
496   return vnet_application_attach (a);
497 }
498
499 static clib_error_t *
500 test_tcp_clients_command_fn (vlib_main_t * vm,
501                              unformat_input_t * input,
502                              vlib_cli_command_t * cmd)
503 {
504   tclient_main_t *tm = &tclient_main;
505   u8 *connect_uri = (u8 *) "tcp://6.0.1.1/1234";
506   u8 *uri;
507   u32 n_clients = 1;
508   int i;
509   u64 tmp;
510
511   tm->bytes_to_send = 8192;
512   vec_free (tm->connect_uri);
513
514   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
515     {
516       if (unformat (input, "nclients %d", &n_clients))
517         ;
518       else if (unformat (input, "mbytes %lld", &tmp))
519         tm->bytes_to_send = tmp << 20;
520       else if (unformat (input, "gbytes %lld", &tmp))
521         tm->bytes_to_send = tmp << 30;
522       else if (unformat (input, "bytes %lld", &tm->bytes_to_send))
523         ;
524       else if (unformat (input, "uri %s", &tm->connect_uri))
525         ;
526       else
527         return clib_error_return (0, "unknown input `%U'",
528                                   format_unformat_error, input);
529     }
530
531   if (tm->is_init == 0)
532     {
533       if (tcp_test_clients_init (vm))
534         return clib_error_return (0, "failed init");
535     }
536
537   tm->ready_connections = 0;
538   tm->expected_connections = n_clients;
539
540   uri = connect_uri;
541   if (tm->connect_uri)
542     uri = tm->connect_uri;
543
544 #if TCP_BUILTIN_CLIENT_PTHREAD
545   /* Start a transmit thread */
546   if (tm->client_thread_handle == 0)
547     {
548       int rv = pthread_create (&tm->client_thread_handle,
549                                NULL /*attr */ ,
550                                tclient_thread_fn, 0);
551       if (rv)
552         {
553           tm->client_thread_handle = 0;
554           return clib_error_return (0, "pthread_create returned %d", rv);
555         }
556     }
557 #endif
558   vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
559   attach_builtin_test_clients ();
560
561   /* Fire off connect requests, in something approaching a normal manner */
562   for (i = 0; i < n_clients; i++)
563     {
564       vl_api_connect_uri_t *cmp;
565       cmp = vl_msg_api_alloc_as_if_client (sizeof (*cmp));
566       memset (cmp, 0, sizeof (*cmp));
567
568       cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
569       cmp->client_index = tm->my_client_index;
570       cmp->context = ntohl (0xfeedface);
571       memcpy (cmp->uri, uri, strlen ((char *) uri) + 1);
572       vl_msg_api_send_shmem (tm->vl_input_queue, (u8 *) & cmp);
573     }
574
575   tm->run_test = 1;
576
577   return 0;
578 }
579
580 /* *INDENT-OFF* */
581 #if TCP_BUILTIN_CLIENT_VPP_THREAD
582 VLIB_REGISTER_THREAD (builtin_client_reg, static) =
583 {
584   .name = "tcp-builtin-client",
585   .function = tclient_thread_fn,
586   .fixed_count = 1,
587   .count = 1,
588   .no_data_structure_clone = 1,
589 };
590 #endif
591 /* *INDENT-ON* */
592
593 /* *INDENT-OFF* */
594 VLIB_CLI_COMMAND (test_clients_command, static) =
595 {
596   .path = "test tcp clients",
597   .short_help = "test tcp clients [nclients %d]"
598   "[iterations %d] [bytes %d] [uri tcp://6.0.1.1/1234]",
599   .function = test_tcp_clients_command_fn,
600 };
601 /* *INDENT-ON* */
602
603 clib_error_t *
604 tcp_test_clients_main_init (vlib_main_t * vm)
605 {
606   tclient_main_t *tm = &tclient_main;
607   tm->is_init = 0;
608   return 0;
609 }
610
611 VLIB_INIT_FUNCTION (tcp_test_clients_main_init);
612
613 /*
614  * fd.io coding-style-patch-verification: ON
615  *
616  * Local Variables:
617  * eval: (c-set-style "gnu")
618  * End:
619  */