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