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