Session/tcp coverity fixes
[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 = (unix_shared_memory_queue_t *)
278     mp->vpp_event_queue_address;
279
280   tm->vpp_event_queue = (unix_shared_memory_queue_t *)
281     mp->vpp_event_queue_address;
282
283   /*
284    * Setup session
285    */
286   pool_get (tm->sessions, session);
287   memset (session, 0, sizeof (*session));
288   session_index = session - tm->sessions;
289   session->bytes_to_receive = session->bytes_to_send = tm->bytes_to_send;
290
291   session->server_rx_fifo = (svm_fifo_t *) mp->server_rx_fifo;
292   session->server_rx_fifo->client_session_index = session_index;
293   session->server_tx_fifo = (svm_fifo_t *) mp->server_tx_fifo;
294   session->server_tx_fifo->client_session_index = session_index;
295   session->vpp_session_handle = mp->handle;
296
297   /* Add it to the session lookup table */
298   hash_set (tm->session_index_by_vpp_handles, mp->handle, session_index);
299
300   tm->ready_connections++;
301 }
302
303 static int
304 create_api_loopback (tclient_main_t * tm)
305 {
306   vlib_main_t *vm = vlib_get_main ();
307   vl_api_memclnt_create_t _m, *mp = &_m;
308   extern void vl_api_memclnt_create_t_handler (vl_api_memclnt_create_t *);
309   api_main_t *am = &api_main;
310   vl_shmem_hdr_t *shmem_hdr;
311   uword *event_data = 0, event_type;
312   int resolved = 0;
313
314   /*
315    * Create a "loopback" API client connection
316    * Don't do things like this unless you know what you're doing...
317    */
318
319   shmem_hdr = am->shmem_hdr;
320   tm->vl_input_queue = shmem_hdr->vl_input_queue;
321   memset (mp, 0, sizeof (*mp));
322   mp->_vl_msg_id = VL_API_MEMCLNT_CREATE;
323   mp->context = 0xFEEDFACE;
324   mp->input_queue = (u64) tm->vl_input_queue;
325   strncpy ((char *) mp->name, "tcp_tester", sizeof (mp->name) - 1);
326
327   vl_api_memclnt_create_t_handler (mp);
328
329   /* Wait for reply */
330   tm->node_index = vlib_get_current_process (vm)->node_runtime.node_index;
331   vlib_process_wait_for_event_or_clock (vm, 1.0);
332   event_type = vlib_process_get_events (vm, &event_data);
333   switch (event_type)
334     {
335     case 1:
336       resolved = 1;
337       break;
338     case ~0:
339       /* timed out */
340       break;
341     default:
342       clib_warning ("unknown event_type %d", event_type);
343     }
344   if (!resolved)
345     return -1;
346   return 0;
347 }
348
349 #define foreach_tclient_static_api_msg          \
350 _(MEMCLNT_CREATE_REPLY, memclnt_create_reply)   \
351 _(CONNECT_URI_REPLY, connect_uri_reply)
352
353 static clib_error_t *
354 tclient_api_hookup (vlib_main_t * vm)
355 {
356   vl_msg_api_msg_config_t _c, *c = &_c;
357
358   /* Hook up client-side static APIs to our handlers */
359 #define _(N,n) do {                                             \
360     c->id = VL_API_##N;                                         \
361     c->name = #n;                                               \
362     c->handler = vl_api_##n##_t_handler;                        \
363     c->cleanup = vl_noop_handler;                               \
364     c->endian = vl_api_##n##_t_endian;                          \
365     c->print = vl_api_##n##_t_print;                            \
366     c->size = sizeof(vl_api_##n##_t);                           \
367     c->traced = 1; /* trace, so these msgs print */             \
368     c->replay = 0; /* don't replay client create/delete msgs */ \
369     c->message_bounce = 0; /* don't bounce this message */      \
370     vl_msg_api_config(c);} while (0);
371
372   foreach_tclient_static_api_msg;
373 #undef _
374
375   return 0;
376 }
377
378 static int
379 tcp_test_clients_init (vlib_main_t * vm)
380 {
381   tclient_main_t *tm = &tclient_main;
382   int i;
383
384   tclient_api_hookup (vm);
385   if (create_api_loopback (tm))
386     return -1;
387
388   /* Init test data */
389   vec_validate (tm->connect_test_data, 64 * 1024 - 1);
390   for (i = 0; i < vec_len (tm->connect_test_data); i++)
391     tm->connect_test_data[i] = i & 0xff;
392
393   tm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
394   vec_validate (tm->rx_buf, vec_len (tm->connect_test_data) - 1);
395
396   tm->is_init = 1;
397
398   return 0;
399 }
400
401 static void
402 builtin_session_reset_callback (stream_session_t * s)
403 {
404   return;
405 }
406
407 static int
408 builtin_session_connected_callback (u32 app_index, u32 api_context,
409                                     stream_session_t * s, u8 code)
410 {
411   return 0;
412 }
413
414 static int
415 builtin_session_create_callback (stream_session_t * s)
416 {
417   return 0;
418 }
419
420 static void
421 builtin_session_disconnect_callback (stream_session_t * s)
422 {
423   return;
424 }
425
426 static int
427 builtin_server_rx_callback (stream_session_t * s)
428 {
429   return 0;
430 }
431
432 /* *INDENT-OFF* */
433 static session_cb_vft_t builtin_clients = {
434     .session_reset_callback = builtin_session_reset_callback,
435     .session_connected_callback = builtin_session_connected_callback,
436     .session_accept_callback = builtin_session_create_callback,
437     .session_disconnect_callback = builtin_session_disconnect_callback,
438     .builtin_server_rx_callback = builtin_server_rx_callback
439 };
440 /* *INDENT-ON* */
441
442 static int
443 attach_builtin_test_clients ()
444 {
445   vnet_app_attach_args_t _a, *a = &_a;
446   u8 segment_name[128];
447   u32 segment_name_length;
448   u64 options[16];
449
450   segment_name_length = ARRAY_LEN (segment_name);
451
452   memset (a, 0, sizeof (*a));
453   memset (options, 0, sizeof (options));
454
455   a->api_client_index = ~0;
456   a->segment_name = segment_name;
457   a->segment_name_length = segment_name_length;
458   a->session_cb_vft = &builtin_clients;
459
460   options[SESSION_OPTIONS_ACCEPT_COOKIE] = 0x12345678;
461   options[SESSION_OPTIONS_SEGMENT_SIZE] = (2 << 30);    /*$$$$ config / arg */
462   options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_BUILTIN_APP;
463
464   a->options = options;
465
466   return vnet_application_attach (a);
467 }
468
469 static clib_error_t *
470 test_tcp_clients_command_fn (vlib_main_t * vm,
471                              unformat_input_t * input,
472                              vlib_cli_command_t * cmd)
473 {
474   tclient_main_t *tm = &tclient_main;
475   u8 *connect_uri = (u8 *) "tcp://6.0.1.1/1234";
476   u8 *uri;
477   u32 n_clients = 1;
478   int i;
479
480   tm->bytes_to_send = 8192;
481   tm->n_iterations = 1;
482   vec_free (tm->connect_uri);
483
484   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
485     {
486       if (unformat (input, "nclients %d", &n_clients))
487         ;
488       else if (unformat (input, "iterations %d", &tm->n_iterations))
489         ;
490       else if (unformat (input, "bytes %lld", &tm->bytes_to_send))
491         ;
492       else if (unformat (input, "uri %s", &tm->connect_uri))
493         ;
494       else
495         return clib_error_return (0, "unknown input `%U'",
496                                   format_unformat_error, input);
497     }
498
499   if (tm->is_init == 0)
500     {
501       if (tcp_test_clients_init (vm))
502         return clib_error_return (0, "failed init");
503     }
504
505   tm->ready_connections = 0;
506   tm->expected_connections = n_clients;
507
508   uri = connect_uri;
509   if (tm->connect_uri)
510     uri = tm->connect_uri;
511
512 #if TCP_BUILTIN_CLIENT_PTHREAD
513   /* Start a transmit thread */
514   if (tm->client_thread_handle == 0)
515     {
516       int rv = pthread_create (&tm->client_thread_handle,
517                                NULL /*attr */ ,
518                                tclient_thread_fn, 0);
519       if (rv)
520         {
521           tm->client_thread_handle = 0;
522           return clib_error_return (0, "pthread_create returned %d", rv);
523         }
524     }
525 #endif
526   vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
527   attach_builtin_test_clients ();
528
529   /* Fire off connect requests, in something approaching a normal manner */
530   for (i = 0; i < n_clients; i++)
531     {
532       vl_api_connect_uri_t *cmp;
533       cmp = vl_msg_api_alloc_as_if_client (sizeof (*cmp));
534       memset (cmp, 0, sizeof (*cmp));
535
536       cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
537       cmp->client_index = tm->my_client_index;
538       cmp->context = ntohl (0xfeedface);
539       memcpy (cmp->uri, uri, strlen ((char *) uri) + 1);
540       vl_msg_api_send_shmem (tm->vl_input_queue, (u8 *) & cmp);
541     }
542
543   tm->run_test = 1;
544
545   return 0;
546 }
547
548 #if TCP_BUILTIN_CLIENT_VPP_THREAD
549 /* *INDENT-OFF* */
550 VLIB_REGISTER_THREAD (builtin_client_reg, static) = {
551   .name = "tcp-builtin-client",
552   .function = tclient_thread_fn,
553   .fixed_count = 1,
554   .count = 1,
555   .no_data_structure_clone = 1,
556 };
557 /* *INDENT-ON* */
558 #endif
559
560 /* *INDENT-OFF* */
561 VLIB_CLI_COMMAND (test_clients_command, static) =
562 {
563   .path = "test tcp clients",
564   .short_help = "test tcp clients [nclients %d] [iterations %d] [bytes %d] [uri tcp://1.2.3.4/1234]",
565   .function = test_tcp_clients_command_fn,
566 };
567 /* *INDENT-ON* */
568
569 clib_error_t *
570 tcp_test_clients_main_init (vlib_main_t * vm)
571 {
572   tclient_main_t *tm = &tclient_main;
573   tm->is_init = 0;
574   return 0;
575 }
576
577 VLIB_INIT_FUNCTION (tcp_test_clients_main_init);
578
579 /*
580  * fd.io coding-style-patch-verification: ON
581  *
582  * Local Variables:
583  * eval: (c-set-style "gnu")
584  * End:
585  */