session: cleanup attach flags
[vpp.git] / src / uri / uri_tcp_test.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <stdio.h>
17 #include <signal.h>
18 #include <svm/svm_fifo_segment.h>
19 #include <vlibmemory/api.h>
20 #include <vpp/api/vpe_msg_enum.h>
21 #include <vnet/session/application_interface.h>
22
23 #define vl_typedefs             /* define message structures */
24 #include <vpp/api/vpe_all_api_h.h>
25 #undef vl_typedefs
26
27 /* declare message handlers for each api */
28
29 #define vl_endianfun            /* define message structures */
30 #include <vpp/api/vpe_all_api_h.h>
31 #undef vl_endianfun
32
33 /* instantiate all the print functions we know about */
34 #define vl_print(handle, ...)
35 #define vl_printfun
36 #include <vpp/api/vpe_all_api_h.h>
37 #undef vl_printfun
38
39 typedef struct
40 {
41   svm_fifo_t *server_rx_fifo;
42   svm_fifo_t *server_tx_fifo;
43
44   u64 vpp_session_handle;
45   u64 bytes_received;
46   f64 start;
47 } session_t;
48
49 typedef enum
50 {
51   STATE_START,
52   STATE_ATTACHED,
53   STATE_READY,
54   STATE_DISCONNECTING,
55   STATE_FAILED
56 } connection_state_t;
57
58 typedef struct
59 {
60   /* vpe input queue */
61   unix_shared_memory_queue_t *vl_input_queue;
62
63   /* API client handle */
64   u32 my_client_index;
65
66   /* The URI we're playing with */
67   u8 *uri;
68
69   /* Session pool */
70   session_t *sessions;
71
72   /* Hash table for disconnect processing */
73   uword *session_index_by_vpp_handles;
74
75   /* intermediate rx buffer */
76   u8 *rx_buf;
77
78   /* URI for slave's connect */
79   u8 *connect_uri;
80
81   u32 connected_session_index;
82
83   int i_am_master;
84
85   /* drop all packets */
86   int drop_packets;
87
88   /* Our event queue */
89   unix_shared_memory_queue_t *our_event_queue;
90
91   /* $$$ single thread only for the moment */
92   unix_shared_memory_queue_t *vpp_event_queue;
93
94   pid_t my_pid;
95
96   /* For deadman timers */
97   clib_time_t clib_time;
98
99   /* State of the connection, shared between msg RX thread and main thread */
100   volatile connection_state_t state;
101
102   /* Signal variables */
103   volatile int time_to_stop;
104   volatile int time_to_print_stats;
105
106   u32 configured_segment_size;
107
108   /* VNET_API_ERROR_FOO -> "Foo" hash table */
109   uword *error_string_by_error_number;
110
111   u8 *connect_test_data;
112   pthread_t client_rx_thread_handle;
113   u32 client_bytes_received;
114   u8 test_return_packets;
115   u64 bytes_to_send;
116
117   /* convenience */
118   svm_fifo_segment_main_t *segment_main;
119 } uri_tcp_test_main_t;
120
121 uri_tcp_test_main_t uri_tcp_test_main;
122
123 #if CLIB_DEBUG > 0
124 #define NITER 10000
125 #else
126 #define NITER 4000000
127 #endif
128
129 static u8 *
130 format_api_error (u8 * s, va_list * args)
131 {
132   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
133   i32 error = va_arg (*args, u32);
134   uword *p;
135
136   p = hash_get (utm->error_string_by_error_number, -error);
137
138   if (p)
139     s = format (s, "%s", p[0]);
140   else
141     s = format (s, "%d", error);
142   return s;
143 }
144
145 static void
146 init_error_string_table (uri_tcp_test_main_t * utm)
147 {
148   utm->error_string_by_error_number = hash_create (0, sizeof (uword));
149
150 #define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s);
151   foreach_vnet_api_error;
152 #undef _
153
154   hash_set (utm->error_string_by_error_number, 99, "Misc");
155 }
156
157 int
158 wait_for_state_change (uri_tcp_test_main_t * utm, connection_state_t state)
159 {
160 #if CLIB_DEBUG > 0
161 #define TIMEOUT 600.0
162 #else
163 #define TIMEOUT 600.0
164 #endif
165
166   f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT;
167
168   while (clib_time_now (&utm->clib_time) < timeout)
169     {
170       if (utm->state == state)
171         return 0;
172       if (utm->state == STATE_FAILED)
173         return -1;
174       if (utm->time_to_stop == 1)
175         return 0;
176     }
177   clib_warning ("timeout waiting for STATE_READY");
178   return -1;
179 }
180
181 void
182 application_send_attach (uri_tcp_test_main_t * utm)
183 {
184   vl_api_application_attach_t *bmp;
185   u32 fifo_size = 4 << 20;
186   bmp = vl_msg_api_alloc (sizeof (*bmp));
187   memset (bmp, 0, sizeof (*bmp));
188
189   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
190   bmp->client_index = utm->my_client_index;
191   bmp->context = ntohl (0xfeedface);
192   bmp->options[APP_OPTIONS_FLAGS] =
193     APP_OPTIONS_FLAGS_ACCEPT_REDIRECT | APP_OPTIONS_FLAGS_ADD_SEGMENT;
194   bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 16;
195   bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = fifo_size;
196   bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = fifo_size;
197   bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20;
198   bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20;
199   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
200 }
201
202 int
203 application_attach (uri_tcp_test_main_t * utm)
204 {
205   application_send_attach (utm);
206   if (wait_for_state_change (utm, STATE_ATTACHED))
207     {
208       clib_warning ("timeout waiting for STATE_ATTACHED");
209       return -1;
210     }
211   return 0;
212 }
213
214 void
215 application_detach (uri_tcp_test_main_t * utm)
216 {
217   vl_api_application_detach_t *bmp;
218   bmp = vl_msg_api_alloc (sizeof (*bmp));
219   memset (bmp, 0, sizeof (*bmp));
220
221   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
222   bmp->client_index = utm->my_client_index;
223   bmp->context = ntohl (0xfeedface);
224   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
225 }
226
227 static void
228 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
229                                            mp)
230 {
231   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
232   svm_fifo_segment_create_args_t _a, *a = &_a;
233   int rv;
234
235   if (mp->retval)
236     {
237       clib_warning ("attach failed: %U", format_api_error,
238                     clib_net_to_host_u32 (mp->retval));
239       utm->state = STATE_FAILED;
240       return;
241     }
242
243   if (mp->segment_name_length == 0)
244     {
245       clib_warning ("segment_name_length zero");
246       return;
247     }
248
249   memset (a, 0, sizeof (*a));
250   a->segment_name = (char *) mp->segment_name;
251   a->segment_size = mp->segment_size;
252
253   ASSERT (mp->app_event_queue_address);
254
255   /* Attach to the segment vpp created */
256   rv = svm_fifo_segment_attach (a);
257   if (rv)
258     {
259       clib_warning ("svm_fifo_segment_attach ('%s') failed",
260                     mp->segment_name);
261       return;
262     }
263
264   utm->our_event_queue =
265     uword_to_pointer (mp->app_event_queue_address,
266                       unix_shared_memory_queue_t *);
267   utm->state = STATE_ATTACHED;
268 }
269
270 static void
271 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
272                                            mp)
273 {
274   if (mp->retval)
275     clib_warning ("detach returned with err: %d", mp->retval);
276 }
277
278 static void
279 stop_signal (int signum)
280 {
281   uri_tcp_test_main_t *um = &uri_tcp_test_main;
282
283   um->time_to_stop = 1;
284 }
285
286 static void
287 stats_signal (int signum)
288 {
289   uri_tcp_test_main_t *um = &uri_tcp_test_main;
290
291   um->time_to_print_stats = 1;
292 }
293
294 static clib_error_t *
295 setup_signal_handlers (void)
296 {
297   signal (SIGINT, stats_signal);
298   signal (SIGQUIT, stop_signal);
299   signal (SIGTERM, stop_signal);
300
301   return 0;
302 }
303
304 void
305 vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
306 {
307   clib_warning ("BUG");
308 }
309
310 int
311 connect_to_vpp (char *name)
312 {
313   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
314   api_main_t *am = &api_main;
315
316   if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
317     return -1;
318
319   utm->vl_input_queue = am->shmem_hdr->vl_input_queue;
320   utm->my_client_index = am->my_client_index;
321
322   return 0;
323 }
324
325 static void
326 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
327 {
328   svm_fifo_segment_create_args_t _a, *a = &_a;
329   int rv;
330
331   memset (a, 0, sizeof (*a));
332   a->segment_name = (char *) mp->segment_name;
333   a->segment_size = mp->segment_size;
334   /* Attach to the segment vpp created */
335   rv = svm_fifo_segment_attach (a);
336   if (rv)
337     {
338       clib_warning ("svm_fifo_segment_attach ('%s') failed",
339                     mp->segment_name);
340       return;
341     }
342   clib_warning ("Mapped new segment '%s' size %d", mp->segment_name,
343                 mp->segment_size);
344 }
345
346 static void
347 session_print_stats (uri_tcp_test_main_t * utm, session_t * session)
348 {
349   f64 deltat;
350   u64 bytes;
351
352   deltat = clib_time_now (&utm->clib_time) - session->start;
353   bytes = utm->i_am_master ? session->bytes_received : utm->bytes_to_send;
354   fformat (stdout, "Finished in %.6f\n", deltat);
355   fformat (stdout, "%.4f Gbit/second\n", (bytes * 8.0) / deltat / 1e9);
356 }
357
358 static void
359 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
360 {
361   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
362   session_t *session = 0;
363   vl_api_disconnect_session_reply_t *rmp;
364   uword *p;
365   int rv = 0;
366
367   p = hash_get (utm->session_index_by_vpp_handles, mp->handle);
368
369   if (p)
370     {
371       session = pool_elt_at_index (utm->sessions, p[0]);
372       hash_unset (utm->session_index_by_vpp_handles, mp->handle);
373       pool_put (utm->sessions, session);
374     }
375   else
376     {
377       clib_warning ("couldn't find session key %llx", mp->handle);
378       rv = -11;
379     }
380
381 //  utm->time_to_stop = 1;
382
383   rmp = vl_msg_api_alloc (sizeof (*rmp));
384   memset (rmp, 0, sizeof (*rmp));
385
386   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
387   rmp->retval = rv;
388   rmp->handle = mp->handle;
389   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
390
391   if (session)
392     session_print_stats (utm, session);
393 }
394
395 static void
396 vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
397 {
398   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
399   vl_api_reset_session_reply_t *rmp;
400   uword *p;
401   int rv = 0;
402
403   p = hash_get (utm->session_index_by_vpp_handles, mp->handle);
404
405   if (p)
406     {
407       clib_warning ("got reset");
408       /* Cleanup later */
409       utm->time_to_stop = 1;
410     }
411   else
412     {
413       clib_warning ("couldn't find session key %llx", mp->handle);
414       rv = -11;
415     }
416
417   rmp = vl_msg_api_alloc (sizeof (*rmp));
418   memset (rmp, 0, sizeof (*rmp));
419   rmp->_vl_msg_id = ntohs (VL_API_RESET_SESSION_REPLY);
420   rmp->retval = rv;
421   rmp->handle = mp->handle;
422   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
423 }
424
425 void
426 client_handle_fifo_event_rx (uri_tcp_test_main_t * utm,
427                              session_fifo_event_t * e)
428 {
429   svm_fifo_t *rx_fifo;
430   int n_read, bytes, i;
431
432   rx_fifo = e->fifo;
433
434   bytes = svm_fifo_max_dequeue (rx_fifo);
435   /* Allow enqueuing of new event */
436   svm_fifo_unset_event (rx_fifo);
437
438   /* Read the bytes */
439   do
440     {
441       n_read = svm_fifo_dequeue_nowait (rx_fifo,
442                                         clib_min (vec_len (utm->rx_buf),
443                                                   bytes), utm->rx_buf);
444       if (n_read > 0)
445         {
446           bytes -= n_read;
447           if (utm->test_return_packets)
448             {
449               for (i = 0; i < n_read; i++)
450                 {
451                   if (utm->rx_buf[i]
452                       != ((utm->client_bytes_received + i) & 0xff))
453                     {
454                       clib_warning ("error at byte %lld, 0x%x not 0x%x",
455                                     utm->client_bytes_received + i,
456                                     utm->rx_buf[i],
457                                     ((utm->client_bytes_received +
458                                       i) & 0xff));
459                     }
460                 }
461             }
462           utm->client_bytes_received += n_read;
463         }
464       else
465         {
466           if (n_read == -2)
467             {
468 //            clib_warning ("weird!");
469               break;
470             }
471         }
472
473     }
474   while (bytes > 0);
475 }
476
477 void
478 client_handle_event_queue (uri_tcp_test_main_t * utm)
479 {
480   session_fifo_event_t _e, *e = &_e;;
481
482   unix_shared_memory_queue_sub (utm->our_event_queue, (u8 *) e,
483                                 0 /* nowait */ );
484   switch (e->event_type)
485     {
486     case FIFO_EVENT_APP_RX:
487       client_handle_fifo_event_rx (utm, e);
488       break;
489
490     case FIFO_EVENT_DISCONNECT:
491       return;
492
493     default:
494       clib_warning ("unknown event type %d", e->event_type);
495       break;
496     }
497 }
498
499 static void *
500 client_rx_thread_fn (void *arg)
501 {
502   session_fifo_event_t _e, *e = &_e;
503   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
504
505   utm->client_bytes_received = 0;
506   while (1)
507     {
508       unix_shared_memory_queue_sub (utm->our_event_queue, (u8 *) e,
509                                     0 /* nowait */ );
510       switch (e->event_type)
511         {
512         case FIFO_EVENT_APP_RX:
513           client_handle_fifo_event_rx (utm, e);
514           break;
515
516         case FIFO_EVENT_DISCONNECT:
517           return 0;
518         default:
519           clib_warning ("unknown event type %d", e->event_type);
520           break;
521         }
522
523       if (PREDICT_FALSE (utm->time_to_stop == 1))
524         break;
525     }
526   pthread_exit (0);
527 }
528
529
530 static void
531 vl_api_connect_session_reply_t_handler (vl_api_connect_session_reply_t * mp)
532 {
533   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
534   session_t *session;
535   u32 session_index;
536   svm_fifo_t *rx_fifo, *tx_fifo;
537   int rv;
538
539   if (mp->retval)
540     {
541       clib_warning ("connection failed with code: %U", format_api_error,
542                     clib_net_to_host_u32 (mp->retval));
543       utm->state = STATE_FAILED;
544       return;
545     }
546   else
547     {
548       clib_warning ("connected with local ip %U port %d", format_ip46_address,
549                     mp->lcl_ip, mp->is_ip4,
550                     clib_net_to_host_u16 (mp->lcl_port));
551     }
552
553   utm->vpp_event_queue =
554     uword_to_pointer (mp->vpp_event_queue_address,
555                       unix_shared_memory_queue_t *);
556
557   /*
558    * Setup session
559    */
560
561   pool_get (utm->sessions, session);
562   session_index = session - utm->sessions;
563
564   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
565   rx_fifo->client_session_index = session_index;
566   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
567   tx_fifo->client_session_index = session_index;
568
569   session->server_rx_fifo = rx_fifo;
570   session->server_tx_fifo = tx_fifo;
571   session->vpp_session_handle = mp->handle;
572   session->start = clib_time_now (&utm->clib_time);
573
574   /* Save handle */
575   utm->connected_session_index = session_index;
576   utm->state = STATE_READY;
577
578   /* Add it to lookup table */
579   hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index);
580
581   /* Start RX thread */
582   rv = pthread_create (&utm->client_rx_thread_handle,
583                        NULL /*attr */ , client_rx_thread_fn, 0);
584   if (rv)
585     {
586       clib_warning ("pthread_create returned %d", rv);
587       rv = VNET_API_ERROR_SYSCALL_ERROR_1;
588     }
589 }
590
591 static void
592 send_test_chunk (uri_tcp_test_main_t * utm, svm_fifo_t * tx_fifo, int mypid,
593                  u32 bytes)
594 {
595   u8 *test_data = utm->connect_test_data;
596   u64 bytes_sent = 0;
597   int test_buf_offset = 0;
598   u32 bytes_to_snd;
599   u32 queue_max_chunk = 128 << 10, actual_write;
600   session_fifo_event_t evt;
601   int rv;
602
603   bytes_to_snd = (bytes == 0) ? vec_len (test_data) : bytes;
604   if (bytes_to_snd > vec_len (test_data))
605     bytes_to_snd = vec_len (test_data);
606
607   while (bytes_to_snd > 0 && !utm->time_to_stop)
608     {
609       actual_write = (bytes_to_snd > queue_max_chunk) ?
610         queue_max_chunk : bytes_to_snd;
611       rv = svm_fifo_enqueue_nowait (tx_fifo, actual_write,
612                                     test_data + test_buf_offset);
613
614       if (rv > 0)
615         {
616           bytes_to_snd -= rv;
617           test_buf_offset += rv;
618           bytes_sent += rv;
619
620           if (svm_fifo_set_event (tx_fifo))
621             {
622               /* Fabricate TX event, send to vpp */
623               evt.fifo = tx_fifo;
624               evt.event_type = FIFO_EVENT_APP_TX;
625
626               unix_shared_memory_queue_add (utm->vpp_event_queue,
627                                             (u8 *) & evt,
628                                             0 /* do wait for mutex */ );
629             }
630         }
631     }
632 }
633
634 void
635 client_send_data (uri_tcp_test_main_t * utm)
636 {
637   u8 *test_data = utm->connect_test_data;
638   int mypid = getpid ();
639   session_t *session;
640   svm_fifo_t *tx_fifo;
641   u32 n_iterations, leftover;
642   int i;
643
644   session = pool_elt_at_index (utm->sessions, utm->connected_session_index);
645   tx_fifo = session->server_tx_fifo;
646
647   ASSERT (vec_len (test_data) > 0);
648
649   vec_validate (utm->rx_buf, vec_len (test_data) - 1);
650   n_iterations = utm->bytes_to_send / vec_len (test_data);
651
652   for (i = 0; i < n_iterations; i++)
653     {
654       send_test_chunk (utm, tx_fifo, mypid, 0);
655       if (utm->time_to_stop)
656         break;
657     }
658
659   leftover = utm->bytes_to_send % vec_len (test_data);
660   if (leftover)
661     send_test_chunk (utm, tx_fifo, mypid, leftover);
662
663   if (!utm->drop_packets)
664     {
665       f64 timeout = clib_time_now (&utm->clib_time) + 10;
666
667       /* Wait for the outstanding packets */
668       while (utm->client_bytes_received <
669              vec_len (test_data) * n_iterations + leftover)
670         {
671           if (clib_time_now (&utm->clib_time) > timeout)
672             {
673               clib_warning ("timed out waiting for the missing packets");
674               break;
675             }
676         }
677     }
678   utm->time_to_stop = 1;
679 }
680
681 void
682 client_send_connect (uri_tcp_test_main_t * utm)
683 {
684   vl_api_connect_uri_t *cmp;
685   cmp = vl_msg_api_alloc (sizeof (*cmp));
686   memset (cmp, 0, sizeof (*cmp));
687
688   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
689   cmp->client_index = utm->my_client_index;
690   cmp->context = ntohl (0xfeedface);
691   memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri));
692   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp);
693 }
694
695 int
696 client_connect (uri_tcp_test_main_t * utm)
697 {
698   client_send_connect (utm);
699   if (wait_for_state_change (utm, STATE_READY))
700     {
701       clib_warning ("Connect failed");
702       return -1;
703     }
704   return 0;
705 }
706
707 void
708 client_send_disconnect (uri_tcp_test_main_t * utm)
709 {
710   session_t *connected_session;
711   vl_api_disconnect_session_t *dmp;
712   connected_session = pool_elt_at_index (utm->sessions,
713                                          utm->connected_session_index);
714   dmp = vl_msg_api_alloc (sizeof (*dmp));
715   memset (dmp, 0, sizeof (*dmp));
716   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
717   dmp->client_index = utm->my_client_index;
718   dmp->handle = connected_session->vpp_session_handle;
719   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & dmp);
720 }
721
722 int
723 client_disconnect (uri_tcp_test_main_t * utm)
724 {
725   client_send_disconnect (utm);
726   clib_warning ("Sent disconnect");
727   if (wait_for_state_change (utm, STATE_START))
728     {
729       clib_warning ("Disconnect failed");
730       return -1;
731     }
732   return 0;
733 }
734
735 static void
736 client_test (uri_tcp_test_main_t * utm)
737 {
738   int i;
739
740   if (application_attach (utm))
741     return;
742
743   if (client_connect (utm))
744     {
745       application_detach (utm);
746       return;
747     }
748
749   /* Init test data */
750   vec_validate (utm->connect_test_data, 128 * 1024 - 1);
751   for (i = 0; i < vec_len (utm->connect_test_data); i++)
752     utm->connect_test_data[i] = i & 0xff;
753
754   /* Start send */
755   client_send_data (utm);
756
757   /* Disconnect */
758   client_disconnect (utm);
759
760   application_detach (utm);
761 }
762
763 static void
764 vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
765 {
766   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
767
768   if (mp->retval)
769     {
770       clib_warning ("bind failed: %U", format_api_error,
771                     clib_net_to_host_u32 (mp->retval));
772       utm->state = STATE_FAILED;
773       return;
774     }
775
776   utm->state = STATE_READY;
777 }
778
779 static void
780 vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
781 {
782   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
783
784   if (mp->retval != 0)
785     clib_warning ("returned %d", ntohl (mp->retval));
786
787   utm->state = STATE_START;
788 }
789
790 u8 *
791 format_ip4_address (u8 * s, va_list * args)
792 {
793   u8 *a = va_arg (*args, u8 *);
794   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
795 }
796
797 u8 *
798 format_ip6_address (u8 * s, va_list * args)
799 {
800   ip6_address_t *a = va_arg (*args, ip6_address_t *);
801   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
802
803   i_max_n_zero = ARRAY_LEN (a->as_u16);
804   max_n_zeros = 0;
805   i_first_zero = i_max_n_zero;
806   n_zeros = 0;
807   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
808     {
809       u32 is_zero = a->as_u16[i] == 0;
810       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
811         {
812           i_first_zero = i;
813           n_zeros = 0;
814         }
815       n_zeros += is_zero;
816       if ((!is_zero && n_zeros > max_n_zeros)
817           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
818         {
819           i_max_n_zero = i_first_zero;
820           max_n_zeros = n_zeros;
821           i_first_zero = ARRAY_LEN (a->as_u16);
822           n_zeros = 0;
823         }
824     }
825
826   last_double_colon = 0;
827   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
828     {
829       if (i == i_max_n_zero && max_n_zeros > 1)
830         {
831           s = format (s, "::");
832           i += max_n_zeros - 1;
833           last_double_colon = 1;
834         }
835       else
836         {
837           s = format (s, "%s%x",
838                       (last_double_colon || i == 0) ? "" : ":",
839                       clib_net_to_host_u16 (a->as_u16[i]));
840           last_double_colon = 0;
841         }
842     }
843
844   return s;
845 }
846
847 /* Format an IP46 address. */
848 u8 *
849 format_ip46_address (u8 * s, va_list * args)
850 {
851   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
852   ip46_type_t type = va_arg (*args, ip46_type_t);
853   int is_ip4 = 1;
854
855   switch (type)
856     {
857     case IP46_TYPE_ANY:
858       is_ip4 = ip46_address_is_ip4 (ip46);
859       break;
860     case IP46_TYPE_IP4:
861       is_ip4 = 1;
862       break;
863     case IP46_TYPE_IP6:
864       is_ip4 = 0;
865       break;
866     }
867
868   return is_ip4 ?
869     format (s, "%U", format_ip4_address, &ip46->ip4) :
870     format (s, "%U", format_ip6_address, &ip46->ip6);
871 }
872
873 static void
874 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
875 {
876   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
877   vl_api_accept_session_reply_t *rmp;
878   svm_fifo_t *rx_fifo, *tx_fifo;
879   session_t *session;
880   static f64 start_time;
881   u32 session_index;
882   u8 *ip_str;
883
884   if (start_time == 0.0)
885     start_time = clib_time_now (&utm->clib_time);
886
887   ip_str = format (0, "%U", format_ip46_address, &mp->ip, mp->is_ip4);
888   clib_warning ("Accepted session from: %s:%d", ip_str,
889                 clib_net_to_host_u16 (mp->port));
890   utm->vpp_event_queue =
891     uword_to_pointer (mp->vpp_event_queue_address,
892                       unix_shared_memory_queue_t *);
893
894   /* Allocate local session and set it up */
895   pool_get (utm->sessions, session);
896   session_index = session - utm->sessions;
897
898   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
899   rx_fifo->client_session_index = session_index;
900   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
901   tx_fifo->client_session_index = session_index;
902
903   session->server_rx_fifo = rx_fifo;
904   session->server_tx_fifo = tx_fifo;
905
906   /* Add it to lookup table */
907   hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index);
908
909   utm->state = STATE_READY;
910
911   /* Stats printing */
912   if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0)
913     {
914       f64 now = clib_time_now (&utm->clib_time);
915       fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
916                pool_elts (utm->sessions), now - start_time,
917                (f64) pool_elts (utm->sessions) / (now - start_time));
918     }
919
920   /*
921    * Send accept reply to vpp
922    */
923   rmp = vl_msg_api_alloc (sizeof (*rmp));
924   memset (rmp, 0, sizeof (*rmp));
925   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
926   rmp->handle = mp->handle;
927   rmp->context = mp->context;
928   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & rmp);
929
930   session->bytes_received = 0;
931   session->start = clib_time_now (&utm->clib_time);
932 }
933
934 void
935 server_handle_fifo_event_rx (uri_tcp_test_main_t * utm,
936                              session_fifo_event_t * e)
937 {
938   svm_fifo_t *rx_fifo, *tx_fifo;
939   int n_read;
940   session_fifo_event_t evt;
941   unix_shared_memory_queue_t *q;
942   session_t *session;
943   int rv;
944   u32 max_dequeue, offset, max_transfer, rx_buf_len;
945
946   rx_buf_len = vec_len (utm->rx_buf);
947   rx_fifo = e->fifo;
948   session = &utm->sessions[rx_fifo->client_session_index];
949   tx_fifo = session->server_tx_fifo;
950
951   max_dequeue = svm_fifo_max_dequeue (rx_fifo);
952   /* Allow enqueuing of a new event */
953   svm_fifo_unset_event (rx_fifo);
954
955   if (PREDICT_FALSE (max_dequeue == 0))
956     {
957       return;
958     }
959
960   /* Read the max_dequeue */
961   do
962     {
963       max_transfer = clib_min (rx_buf_len, max_dequeue);
964       n_read = svm_fifo_dequeue_nowait (rx_fifo, max_transfer, utm->rx_buf);
965       if (n_read > 0)
966         {
967           max_dequeue -= n_read;
968           session->bytes_received += n_read;
969         }
970
971       /* Reflect if a non-drop session */
972       if (!utm->drop_packets && n_read > 0)
973         {
974           offset = 0;
975           do
976             {
977               rv = svm_fifo_enqueue_nowait (tx_fifo, n_read,
978                                             &utm->rx_buf[offset]);
979               if (rv > 0)
980                 {
981                   n_read -= rv;
982                   offset += rv;
983                 }
984             }
985           while ((rv <= 0 || n_read > 0) && !utm->time_to_stop);
986
987           /* If event wasn't set, add one */
988           if (svm_fifo_set_event (tx_fifo))
989             {
990               /* Fabricate TX event, send to vpp */
991               evt.fifo = tx_fifo;
992               evt.event_type = FIFO_EVENT_APP_TX;
993
994               q = utm->vpp_event_queue;
995               unix_shared_memory_queue_add (q, (u8 *) & evt,
996                                             1 /* do wait for mutex */ );
997             }
998         }
999     }
1000   while ((n_read < 0 || max_dequeue > 0) && !utm->time_to_stop);
1001 }
1002
1003 void
1004 server_handle_event_queue (uri_tcp_test_main_t * utm)
1005 {
1006   session_fifo_event_t _e, *e = &_e;
1007
1008   while (1)
1009     {
1010       unix_shared_memory_queue_sub (utm->our_event_queue, (u8 *) e,
1011                                     0 /* nowait */ );
1012       switch (e->event_type)
1013         {
1014         case FIFO_EVENT_APP_RX:
1015           server_handle_fifo_event_rx (utm, e);
1016           break;
1017
1018         case FIFO_EVENT_DISCONNECT:
1019           return;
1020
1021         default:
1022           clib_warning ("unknown event type %d", e->event_type);
1023           break;
1024         }
1025       if (PREDICT_FALSE (utm->time_to_stop == 1))
1026         break;
1027       if (PREDICT_FALSE (utm->time_to_print_stats == 1))
1028         {
1029           utm->time_to_print_stats = 0;
1030           fformat (stdout, "%d connections\n", pool_elts (utm->sessions));
1031         }
1032     }
1033 }
1034
1035 void
1036 server_send_listen (uri_tcp_test_main_t * utm)
1037 {
1038   vl_api_bind_uri_t *bmp;
1039   bmp = vl_msg_api_alloc (sizeof (*bmp));
1040   memset (bmp, 0, sizeof (*bmp));
1041
1042   bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
1043   bmp->client_index = utm->my_client_index;
1044   bmp->context = ntohl (0xfeedface);
1045   memcpy (bmp->uri, utm->uri, vec_len (utm->uri));
1046   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp);
1047 }
1048
1049 int
1050 server_listen (uri_tcp_test_main_t * utm)
1051 {
1052   server_send_listen (utm);
1053   if (wait_for_state_change (utm, STATE_READY))
1054     {
1055       clib_warning ("timeout waiting for STATE_READY");
1056       return -1;
1057     }
1058   return 0;
1059 }
1060
1061 void
1062 server_send_unbind (uri_tcp_test_main_t * utm)
1063 {
1064   vl_api_unbind_uri_t *ump;
1065
1066   ump = vl_msg_api_alloc (sizeof (*ump));
1067   memset (ump, 0, sizeof (*ump));
1068
1069   ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
1070   ump->client_index = utm->my_client_index;
1071   memcpy (ump->uri, utm->uri, vec_len (utm->uri));
1072   vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump);
1073 }
1074
1075 int
1076 server_unbind (uri_tcp_test_main_t * utm)
1077 {
1078   server_send_unbind (utm);
1079   if (wait_for_state_change (utm, STATE_START))
1080     {
1081       clib_warning ("timeout waiting for STATE_START");
1082       return -1;
1083     }
1084   return 0;
1085 }
1086
1087 void
1088 server_test (uri_tcp_test_main_t * utm)
1089 {
1090   if (application_attach (utm))
1091     return;
1092
1093   /* Bind to uri */
1094   if (server_listen (utm))
1095     return;
1096
1097   /* Enter handle event loop */
1098   server_handle_event_queue (utm);
1099
1100   /* Cleanup */
1101   server_send_unbind (utm);
1102
1103   application_detach (utm);
1104
1105   fformat (stdout, "Test complete...\n");
1106 }
1107
1108 static void
1109 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
1110                                            mp)
1111 {
1112   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
1113   session_t *session;
1114
1115   if (mp->retval)
1116     {
1117       clib_warning ("vpp complained about disconnect: %d",
1118                     ntohl (mp->retval));
1119     }
1120
1121   utm->state = STATE_START;
1122   session = pool_elt_at_index (utm->sessions, utm->connected_session_index);
1123   if (session)
1124     session_print_stats (utm, session);
1125 }
1126
1127 #define foreach_uri_msg                                 \
1128 _(BIND_URI_REPLY, bind_uri_reply)                       \
1129 _(UNBIND_URI_REPLY, unbind_uri_reply)                   \
1130 _(ACCEPT_SESSION, accept_session)                       \
1131 _(CONNECT_SESSION_REPLY, connect_session_reply)         \
1132 _(DISCONNECT_SESSION, disconnect_session)               \
1133 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)   \
1134 _(RESET_SESSION, reset_session)                         \
1135 _(APPLICATION_ATTACH_REPLY, application_attach_reply)   \
1136 _(APPLICATION_DETACH_REPLY, application_detach_reply)   \
1137 _(MAP_ANOTHER_SEGMENT, map_another_segment)             \
1138
1139 void
1140 uri_api_hookup (uri_tcp_test_main_t * utm)
1141 {
1142 #define _(N,n)                                                  \
1143     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1144                            vl_api_##n##_t_handler,              \
1145                            vl_noop_handler,                     \
1146                            vl_api_##n##_t_endian,               \
1147                            vl_api_##n##_t_print,                \
1148                            sizeof(vl_api_##n##_t), 1);
1149   foreach_uri_msg;
1150 #undef _
1151 }
1152
1153 int
1154 main (int argc, char **argv)
1155 {
1156   uri_tcp_test_main_t *utm = &uri_tcp_test_main;
1157   unformat_input_t _argv, *a = &_argv;
1158   u8 *chroot_prefix;
1159   u8 *heap, *uri = 0;
1160   u8 *bind_uri = (u8 *) "tcp://0.0.0.0/1234";
1161   u8 *connect_uri = (u8 *) "tcp://6.0.1.2/1234";
1162   u64 bytes_to_send = 64 << 10, mbytes;
1163   u32 tmp;
1164   mheap_t *h;
1165   session_t *session;
1166   int i;
1167   int i_am_master = 1, drop_packets = 0, test_return_packets = 0;
1168
1169   clib_mem_init (0, 256 << 20);
1170
1171   heap = clib_mem_get_per_cpu_heap ();
1172   h = mheap_header (heap);
1173
1174   /* make the main heap thread-safe */
1175   h->flags |= MHEAP_FLAG_THREAD_SAFE;
1176
1177   vec_validate (utm->rx_buf, 128 << 10);
1178
1179   utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1180
1181   utm->my_pid = getpid ();
1182   utm->configured_segment_size = 1 << 20;
1183
1184   clib_time_init (&utm->clib_time);
1185   init_error_string_table (utm);
1186   svm_fifo_segment_init (0x200000000ULL, 20);
1187   unformat_init_command_line (a, argv);
1188
1189   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
1190     {
1191       if (unformat (a, "chroot prefix %s", &chroot_prefix))
1192         {
1193           vl_set_memory_root_path ((char *) chroot_prefix);
1194         }
1195       else if (unformat (a, "uri %s", &uri))
1196         ;
1197       else if (unformat (a, "segment-size %dM", &tmp))
1198         utm->configured_segment_size = tmp << 20;
1199       else if (unformat (a, "segment-size %dG", &tmp))
1200         utm->configured_segment_size = tmp << 30;
1201       else if (unformat (a, "master"))
1202         i_am_master = 1;
1203       else if (unformat (a, "slave"))
1204         i_am_master = 0;
1205       else if (unformat (a, "drop"))
1206         drop_packets = 1;
1207       else if (unformat (a, "test"))
1208         test_return_packets = 1;
1209       else if (unformat (a, "mbytes %lld", &mbytes))
1210         {
1211           bytes_to_send = mbytes << 20;
1212         }
1213       else if (unformat (a, "gbytes %lld", &mbytes))
1214         {
1215           bytes_to_send = mbytes << 30;
1216         }
1217       else
1218         {
1219           fformat (stderr, "%s: usage [master|slave]\n");
1220           exit (1);
1221         }
1222     }
1223
1224   if (uri)
1225     {
1226       utm->uri = format (0, "%s%c", uri, 0);
1227       utm->connect_uri = format (0, "%s%c", uri, 0);
1228     }
1229   else
1230     {
1231       utm->uri = format (0, "%s%c", bind_uri, 0);
1232       utm->connect_uri = format (0, "%s%c", connect_uri, 0);
1233     }
1234
1235   utm->i_am_master = i_am_master;
1236   utm->segment_main = &svm_fifo_segment_main;
1237   utm->drop_packets = drop_packets;
1238   utm->test_return_packets = test_return_packets;
1239   utm->bytes_to_send = bytes_to_send;
1240   utm->time_to_stop = 0;
1241
1242   setup_signal_handlers ();
1243   uri_api_hookup (utm);
1244
1245   if (connect_to_vpp (i_am_master ? "uri_tcp_server" : "uri_tcp_client") < 0)
1246     {
1247       svm_region_exit ();
1248       fformat (stderr, "Couldn't connect to vpe, exiting...\n");
1249       exit (1);
1250     }
1251
1252   if (i_am_master == 0)
1253     {
1254       client_test (utm);
1255       vl_client_disconnect_from_vlib ();
1256       exit (0);
1257     }
1258
1259   /* $$$$ hack preallocation */
1260   for (i = 0; i < 200000; i++)
1261     {
1262       pool_get (utm->sessions, session);
1263       memset (session, 0, sizeof (*session));
1264     }
1265   for (i = 0; i < 200000; i++)
1266     pool_put_index (utm->sessions, i);
1267
1268   server_test (utm);
1269
1270   vl_client_disconnect_from_vlib ();
1271   exit (0);
1272 }
1273
1274 /*
1275  * fd.io coding-style-patch-verification: ON
1276  *
1277  * Local Variables:
1278  * eval: (c-set-style "gnu")
1279  * End:
1280  */