Fix builtin tcp client
[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 (1)
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   while (1)
191     {
192       /* Wait until we're told to get busy */
193       while (tm->run_test == 0
194              || (tm->ready_connections != tm->expected_connections))
195         {
196           ts.tv_sec = 0;
197           ts.tv_nsec = 100000000;
198           while (nanosleep (&ts, &tsrem) < 0)
199             ts = tsrem;
200         }
201       tm->run_test = 0;
202       rx_total = 0;
203
204       clib_warning ("Run %d iterations", tm->n_iterations);
205
206       before = clib_time_now (&ttime);
207
208       for (i = 0; i < tm->n_iterations; i++)
209         {
210           session_t *sp;
211
212           do
213             {
214               try_tx = try_rx = 0;
215
216               /* *INDENT-OFF* */
217               pool_foreach (sp, tm->sessions,
218               ({
219                 if (sp->bytes_to_send > 0)
220                   {
221                     send_test_chunk (tm, sp);
222                     try_tx = 1;
223                   }
224               }));
225               pool_foreach (sp, tm->sessions,
226               ({
227                 if (sp->bytes_to_receive > 0)
228                   {
229                     receive_test_chunk (tm, sp);
230                     try_rx = 1;
231                   }
232               }));
233               /* *INDENT-ON* */
234             }
235           while (try_tx || try_rx);
236
237           /* *INDENT-OFF* */
238           pool_foreach (sp, tm->sessions,
239           ({
240             rx_total += sp->bytes_received;
241             sp->bytes_received = 0;
242             sp->bytes_to_send = tm->bytes_to_send;
243           }));
244           /* *INDENT-ON* */
245         }
246       after = clib_time_now (&ttime);
247
248       clib_warning ("Done %d iterations, %lld bytes in %.2f secs",
249                     tm->n_iterations, rx_total, (after - before));
250       if ((after - before) != 0.0)
251         {
252           clib_warning ("%.2f bytes/second full-duplex",
253                         ((f64) rx_total) / (after - before));
254           clib_warning ("%.4f gbit/second full-duplex",
255                         (((f64) rx_total * 8.0) / (after - before)) / 1e9);
256         }
257
258       /* Disconnect sessions... */
259       vec_reset_length (session_indices);
260
261       /* *INDENT-OFF* */
262       pool_foreach (sp, tm->sessions,
263       ({
264         vec_add1 (session_indices, sp - tm->sessions);
265       }));
266       /* *INDENT-ON* */
267
268       for (i = 0; i < vec_len (session_indices); i++)
269         {
270           sp = pool_elt_at_index (tm->sessions, session_indices[i]);
271           dmp = vl_msg_api_alloc_as_if_client (sizeof (*dmp));
272           memset (dmp, 0, sizeof (*dmp));
273           dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
274           dmp->client_index = tm->my_client_index;
275           dmp->handle = sp->vpp_session_handle;
276           vl_msg_api_send_shmem (tm->vl_input_queue, (u8 *) & dmp);
277           pool_put (tm->sessions, sp);
278         }
279     }
280   /* NOTREACHED */
281 #if TCP_BUILTIN_CLIENT_PTHREAD
282   return 0;
283 #endif
284 }
285
286 /* So we don't get "no handler for... " msgs */
287 static void
288 vl_api_memclnt_create_reply_t_handler (vl_api_memclnt_create_reply_t * mp)
289 {
290   vlib_main_t *vm = vlib_get_main ();
291   tclient_main_t *tm = &tclient_main;
292   tm->my_client_index = mp->index;
293   vlib_process_signal_event (vm, tm->node_index, 1 /* evt */ ,
294                              0 /* data */ );
295 }
296
297 static void
298 vl_api_connect_uri_reply_t_handler (vl_api_connect_uri_reply_t * mp)
299 {
300   tclient_main_t *tm = &tclient_main;
301   session_t *session;
302   u32 session_index;
303   i32 retval = /* clib_net_to_host_u32 ( */ mp->retval /*) */ ;
304
305   if (retval < 0)
306     {
307       clib_warning ("connection failed: retval %d", retval);
308       return;
309     }
310
311   tm->our_event_queue =
312     uword_to_pointer (mp->vpp_event_queue_address,
313                       unix_shared_memory_queue_t *);
314   tm->vpp_event_queue =
315     uword_to_pointer (mp->vpp_event_queue_address,
316                       unix_shared_memory_queue_t *);
317
318   /*
319    * Setup session
320    */
321   pool_get (tm->sessions, session);
322   memset (session, 0, sizeof (*session));
323   session_index = session - tm->sessions;
324   session->bytes_to_receive = session->bytes_to_send = tm->bytes_to_send;
325
326   session->server_rx_fifo =
327     uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
328   session->server_rx_fifo->client_session_index = session_index;
329   session->server_tx_fifo =
330     uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
331   session->server_tx_fifo->client_session_index = session_index;
332   session->vpp_session_handle = mp->handle;
333
334   /* Add it to the session lookup table */
335   hash_set (tm->session_index_by_vpp_handles, mp->handle, session_index);
336
337   tm->ready_connections++;
338 }
339
340 static int
341 create_api_loopback (tclient_main_t * tm)
342 {
343   vlib_main_t *vm = vlib_get_main ();
344   vl_api_memclnt_create_t _m, *mp = &_m;
345   extern void vl_api_memclnt_create_t_handler (vl_api_memclnt_create_t *);
346   api_main_t *am = &api_main;
347   vl_shmem_hdr_t *shmem_hdr;
348   uword *event_data = 0, event_type;
349   int resolved = 0;
350
351   /*
352    * Create a "loopback" API client connection
353    * Don't do things like this unless you know what you're doing...
354    */
355
356   shmem_hdr = am->shmem_hdr;
357   tm->vl_input_queue = shmem_hdr->vl_input_queue;
358   memset (mp, 0, sizeof (*mp));
359   mp->_vl_msg_id = VL_API_MEMCLNT_CREATE;
360   mp->context = 0xFEEDFACE;
361   mp->input_queue = pointer_to_uword (tm->vl_input_queue);
362   strncpy ((char *) mp->name, "tcp_tester", sizeof (mp->name) - 1);
363
364   vl_api_memclnt_create_t_handler (mp);
365
366   /* Wait for reply */
367   tm->node_index = vlib_get_current_process (vm)->node_runtime.node_index;
368   vlib_process_wait_for_event_or_clock (vm, 1.0);
369   event_type = vlib_process_get_events (vm, &event_data);
370   switch (event_type)
371     {
372     case 1:
373       resolved = 1;
374       break;
375     case ~0:
376       /* timed out */
377       break;
378     default:
379       clib_warning ("unknown event_type %d", event_type);
380     }
381   if (!resolved)
382     return -1;
383   return 0;
384 }
385
386 #define foreach_tclient_static_api_msg          \
387 _(MEMCLNT_CREATE_REPLY, memclnt_create_reply)   \
388 _(CONNECT_URI_REPLY, connect_uri_reply)
389
390 static clib_error_t *
391 tclient_api_hookup (vlib_main_t * vm)
392 {
393   vl_msg_api_msg_config_t _c, *c = &_c;
394
395   /* Hook up client-side static APIs to our handlers */
396 #define _(N,n) do {                                             \
397     c->id = VL_API_##N;                                         \
398     c->name = #n;                                               \
399     c->handler = vl_api_##n##_t_handler;                        \
400     c->cleanup = vl_noop_handler;                               \
401     c->endian = vl_api_##n##_t_endian;                          \
402     c->print = vl_api_##n##_t_print;                            \
403     c->size = sizeof(vl_api_##n##_t);                           \
404     c->traced = 1; /* trace, so these msgs print */             \
405     c->replay = 0; /* don't replay client create/delete msgs */ \
406     c->message_bounce = 0; /* don't bounce this message */      \
407     vl_msg_api_config(c);} while (0);
408
409   foreach_tclient_static_api_msg;
410 #undef _
411
412   return 0;
413 }
414
415 static int
416 tcp_test_clients_init (vlib_main_t * vm)
417 {
418   tclient_main_t *tm = &tclient_main;
419   int i;
420
421   tclient_api_hookup (vm);
422   if (create_api_loopback (tm))
423     return -1;
424
425   /* Init test data */
426   vec_validate (tm->connect_test_data, 64 * 1024 - 1);
427   for (i = 0; i < vec_len (tm->connect_test_data); i++)
428     tm->connect_test_data[i] = i & 0xff;
429
430   tm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
431   vec_validate (tm->rx_buf, vec_len (tm->connect_test_data) - 1);
432
433   tm->is_init = 1;
434
435   return 0;
436 }
437
438 static void
439 builtin_session_reset_callback (stream_session_t * s)
440 {
441   return;
442 }
443
444 static int
445 builtin_session_create_callback (stream_session_t * s)
446 {
447   return 0;
448 }
449
450 static void
451 builtin_session_disconnect_callback (stream_session_t * s)
452 {
453   return;
454 }
455
456 static int
457 builtin_server_rx_callback (stream_session_t * s)
458 {
459   return 0;
460 }
461
462 /* *INDENT-OFF* */
463 static session_cb_vft_t builtin_clients =
464   {
465     .session_reset_callback = builtin_session_reset_callback,
466     .session_connected_callback = send_session_connected_callback,
467     .session_accept_callback = builtin_session_create_callback,
468     .session_disconnect_callback = builtin_session_disconnect_callback,
469     .builtin_server_rx_callback = builtin_server_rx_callback
470   };
471 /* *INDENT-ON* */
472
473 static int
474 attach_builtin_test_clients ()
475 {
476   tclient_main_t *tm = &tclient_main;
477   vnet_app_attach_args_t _a, *a = &_a;
478   u8 segment_name[128];
479   u32 segment_name_length;
480   u64 options[16];
481
482   segment_name_length = ARRAY_LEN (segment_name);
483
484   memset (a, 0, sizeof (*a));
485   memset (options, 0, sizeof (options));
486
487   a->api_client_index = tm->my_client_index;
488   a->segment_name = segment_name;
489   a->segment_name_length = segment_name_length;
490   a->session_cb_vft = &builtin_clients;
491
492   options[SESSION_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
493   options[SESSION_OPTIONS_SEGMENT_SIZE] = (2 << 30);    /*$$$$ config / arg */
494   options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_BUILTIN_APP;
495
496   a->options = options;
497
498   return vnet_application_attach (a);
499 }
500
501 static clib_error_t *
502 test_tcp_clients_command_fn (vlib_main_t * vm,
503                              unformat_input_t * input,
504                              vlib_cli_command_t * cmd)
505 {
506   tclient_main_t *tm = &tclient_main;
507   u8 *connect_uri = (u8 *) "tcp://6.0.1.1/1234";
508   u8 *uri;
509   u32 n_clients = 1;
510   int i;
511   u64 tmp;
512
513   tm->bytes_to_send = 8192;
514   tm->n_iterations = 1;
515   vec_free (tm->connect_uri);
516
517   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
518     {
519       if (unformat (input, "nclients %d", &n_clients))
520         ;
521       else if (unformat (input, "iterations %d", &tm->n_iterations))
522         ;
523       else if (unformat (input, "mbytes %lld", &tmp))
524         tm->bytes_to_send = tmp << 20;
525       else if (unformat (input, "gbytes %lld", &tmp))
526         tm->bytes_to_send = tmp << 30;
527       else if (unformat (input, "bytes %lld", &tm->bytes_to_send))
528         ;
529       else if (unformat (input, "uri %s", &tm->connect_uri))
530         ;
531       else
532         return clib_error_return (0, "unknown input `%U'",
533                                   format_unformat_error, input);
534     }
535
536   if (tm->is_init == 0)
537     {
538       if (tcp_test_clients_init (vm))
539         return clib_error_return (0, "failed init");
540     }
541
542   tm->ready_connections = 0;
543   tm->expected_connections = n_clients;
544
545   uri = connect_uri;
546   if (tm->connect_uri)
547     uri = tm->connect_uri;
548
549 #if TCP_BUILTIN_CLIENT_PTHREAD
550   /* Start a transmit thread */
551   if (tm->client_thread_handle == 0)
552     {
553       int rv = pthread_create (&tm->client_thread_handle,
554                                NULL /*attr */ ,
555                                tclient_thread_fn, 0);
556       if (rv)
557         {
558           tm->client_thread_handle = 0;
559           return clib_error_return (0, "pthread_create returned %d", rv);
560         }
561     }
562 #endif
563   vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
564   attach_builtin_test_clients ();
565
566   /* Fire off connect requests, in something approaching a normal manner */
567   for (i = 0; i < n_clients; i++)
568     {
569       vl_api_connect_uri_t *cmp;
570       cmp = vl_msg_api_alloc_as_if_client (sizeof (*cmp));
571       memset (cmp, 0, sizeof (*cmp));
572
573       cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
574       cmp->client_index = tm->my_client_index;
575       cmp->context = ntohl (0xfeedface);
576       memcpy (cmp->uri, uri, strlen ((char *) uri) + 1);
577       vl_msg_api_send_shmem (tm->vl_input_queue, (u8 *) & cmp);
578     }
579
580   tm->run_test = 1;
581
582   return 0;
583 }
584
585 /* *INDENT-OFF* */
586 #if TCP_BUILTIN_CLIENT_VPP_THREAD
587 VLIB_REGISTER_THREAD (builtin_client_reg, static) =
588 {
589   .name = "tcp-builtin-client",
590   .function = tclient_thread_fn,
591   .fixed_count = 1,
592   .count = 1,
593   .no_data_structure_clone = 1,
594 };
595 #endif
596 /* *INDENT-ON* */
597
598 /* *INDENT-OFF* */
599 VLIB_CLI_COMMAND (test_clients_command, static) =
600 {
601   .path = "test tcp clients",
602   .short_help = "test tcp clients [nclients %d]"
603   "[iterations %d] [bytes %d] [uri tcp://6.0.1.1/1234]",
604   .function = test_tcp_clients_command_fn,
605 };
606 /* *INDENT-ON* */
607
608 clib_error_t *
609 tcp_test_clients_main_init (vlib_main_t * vm)
610 {
611   tclient_main_t *tm = &tclient_main;
612   tm->is_init = 0;
613   return 0;
614 }
615
616 VLIB_INIT_FUNCTION (tcp_test_clients_main_init);
617
618 /*
619  * fd.io coding-style-patch-verification: ON
620  *
621  * Local Variables:
622  * eval: (c-set-style "gnu")
623  * End:
624  */