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