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