session: support multiple worker binds
[vpp.git] / src / vcl / vcl_test_server.c
1 /*
2  * Copyright (c) 2017-2018 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 <unistd.h>
17 #include <errno.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <time.h>
23 #include <ctype.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <vcl/vcl_test.h>
27 #include <sys/epoll.h>
28 #include <vppinfra/mem.h>
29 #include <pthread.h>
30
31 typedef struct
32 {
33   uint8_t is_alloc;
34   int fd;
35   uint8_t *buf;
36   uint32_t buf_size;
37   sock_test_cfg_t cfg;
38   sock_test_stats_t stats;
39   vppcom_endpt_t endpt;
40   uint8_t ip[16];
41 } vcl_test_server_conn_t;
42
43 typedef struct
44 {
45   uint16_t port;
46   uint32_t address_ip6;
47   u8 proto;
48   u8 workers;
49   vppcom_endpt_t endpt;
50 } vcl_test_server_cfg_t;
51
52 #define SOCK_SERVER_MAX_TEST_CONN  16
53 #define SOCK_SERVER_MAX_EPOLL_EVENTS 16
54
55 typedef struct
56 {
57   uint32_t wrk_index;
58   int listen_fd;
59   int epfd;
60   struct epoll_event wait_events[SOCK_SERVER_MAX_EPOLL_EVENTS];
61   size_t conn_pool_size;
62   vcl_test_server_conn_t *conn_pool;
63   int nfds;
64   pthread_t thread_handle;
65 } vcl_test_server_worker_t;
66
67 typedef struct
68 {
69   vcl_test_server_cfg_t cfg;
70   vcl_test_server_worker_t *workers;
71
72   struct sockaddr_storage servaddr;
73   volatile int worker_fails;
74   volatile int active_workers;
75 } vcl_test_server_main_t;
76
77 static __thread int __wrk_index = 0;
78
79 static vcl_test_server_main_t sock_server_main;
80
81 #define vtfail(_fn, _rv)                                                \
82 {                                                                       \
83   errno = -_rv;                                                         \
84   perror ("ERROR when calling " _fn);                                   \
85   fprintf (stderr, "\nSERVER ERROR: " _fn " failed (errno = %d)!\n", -_rv);\
86   exit (1);                                                             \
87 }
88
89 #define vterr(_fn, _rv)                                                 \
90 {                                                                       \
91   errno = -_rv;                                                         \
92   fprintf (stderr, "\nSERVER ERROR: " _fn " failed (errno = %d)!\n", -_rv);\
93 }
94
95 #define vtwrn(_fmt, _args...)                                           \
96   fprintf (stderr, "\nSERVER ERROR: " _fmt "\n", ##_args)               \
97
98 #define vtinf(_fmt, _args...)                                           \
99   fprintf (stdout, "\nvts<w%u>: " _fmt "\n", __wrk_index, ##_args)      \
100
101 static inline void
102 conn_pool_expand (vcl_test_server_worker_t * wrk, size_t expand_size)
103 {
104   vcl_test_server_conn_t *conn_pool;
105   size_t new_size = wrk->conn_pool_size + expand_size;
106   int i;
107
108   conn_pool = realloc (wrk->conn_pool, new_size * sizeof (*wrk->conn_pool));
109   if (conn_pool)
110     {
111       for (i = wrk->conn_pool_size; i < new_size; i++)
112         {
113           vcl_test_server_conn_t *conn = &conn_pool[i];
114           memset (conn, 0, sizeof (*conn));
115           sock_test_cfg_init (&conn->cfg);
116           sock_test_buf_alloc (&conn->cfg, 1 /* is_rxbuf */ ,
117                                &conn->buf, &conn->buf_size);
118           conn->cfg.txbuf_size = conn->cfg.rxbuf_size;
119         }
120
121       wrk->conn_pool = conn_pool;
122       wrk->conn_pool_size = new_size;
123     }
124   else
125     {
126       vterr ("conn_pool_expand()", -errno);
127     }
128 }
129
130 static inline vcl_test_server_conn_t *
131 conn_pool_alloc (vcl_test_server_worker_t * wrk)
132 {
133   int i;
134
135   for (i = 0; i < wrk->conn_pool_size; i++)
136     {
137       if (!wrk->conn_pool[i].is_alloc)
138         {
139           wrk->conn_pool[i].endpt.ip = wrk->conn_pool[i].ip;
140           wrk->conn_pool[i].is_alloc = 1;
141           return (&wrk->conn_pool[i]);
142         }
143     }
144
145   return 0;
146 }
147
148 static inline void
149 conn_pool_free (vcl_test_server_conn_t * conn)
150 {
151   conn->fd = 0;
152   conn->is_alloc = 0;
153 }
154
155 static inline void
156 sync_config_and_reply (vcl_test_server_conn_t * conn,
157                        sock_test_cfg_t * rx_cfg)
158 {
159   conn->cfg = *rx_cfg;
160   sock_test_buf_alloc (&conn->cfg, 1 /* is_rxbuf */ ,
161                        &conn->buf, &conn->buf_size);
162   conn->cfg.txbuf_size = conn->cfg.rxbuf_size;
163
164   if (conn->cfg.verbose)
165     {
166       vtinf ("(fd %d): Replying to cfg message!\n", conn->fd);
167       sock_test_cfg_dump (&conn->cfg, 0 /* is_client */ );
168     }
169   (void) vcl_test_write (conn->fd, (uint8_t *) & conn->cfg,
170                          sizeof (conn->cfg), NULL, conn->cfg.verbose);
171 }
172
173 static void
174 stream_test_server_start_stop (vcl_test_server_worker_t * wrk,
175                                vcl_test_server_conn_t * conn,
176                                sock_test_cfg_t * rx_cfg)
177 {
178   int client_fd = conn->fd;
179   sock_test_t test = rx_cfg->test;
180
181   if (rx_cfg->ctrl_handle == conn->fd)
182     {
183       int i;
184       clock_gettime (CLOCK_REALTIME, &conn->stats.stop);
185
186       for (i = 0; i < wrk->conn_pool_size; i++)
187         {
188           vcl_test_server_conn_t *tc = &wrk->conn_pool[i];
189
190           if (tc->cfg.ctrl_handle == conn->fd)
191             {
192               sock_test_stats_accumulate (&conn->stats, &tc->stats);
193
194               if (conn->cfg.verbose)
195                 {
196                   static char buf[64];
197
198                   sprintf (buf, "SERVER (fd %d) RESULTS", tc->fd);
199                   sock_test_stats_dump (buf, &tc->stats, 1 /* show_rx */ ,
200                                         test == SOCK_TEST_TYPE_BI
201                                         /* show tx */ ,
202                                         conn->cfg.verbose);
203                 }
204             }
205         }
206
207       sock_test_stats_dump ("SERVER RESULTS", &conn->stats, 1 /* show_rx */ ,
208                             (test == SOCK_TEST_TYPE_BI) /* show_tx */ ,
209                             conn->cfg.verbose);
210       sock_test_cfg_dump (&conn->cfg, 0 /* is_client */ );
211       if (conn->cfg.verbose)
212         {
213           printf ("  sock server main\n"
214                   SOCK_TEST_SEPARATOR_STRING
215                   "       buf:  %p\n"
216                   "  buf size:  %u (0x%08x)\n"
217                   SOCK_TEST_SEPARATOR_STRING,
218                   conn->buf, conn->buf_size, conn->buf_size);
219         }
220
221       sync_config_and_reply (conn, rx_cfg);
222       printf ("\nSERVER (fd %d): %s-directional Stream Test Complete!\n"
223               SOCK_TEST_BANNER_STRING "\n", conn->fd,
224               test == SOCK_TEST_TYPE_BI ? "Bi" : "Uni");
225     }
226   else
227     {
228       printf ("\n" SOCK_TEST_BANNER_STRING
229               "SERVER (fd %d): %s-directional Stream Test!\n"
230               "  Sending client the test cfg to start streaming data...\n",
231               client_fd, test == SOCK_TEST_TYPE_BI ? "Bi" : "Uni");
232
233       rx_cfg->ctrl_handle = (rx_cfg->ctrl_handle == ~0) ? conn->fd :
234         rx_cfg->ctrl_handle;
235
236       sync_config_and_reply (conn, rx_cfg);
237
238       /* read the 1st chunk, record start time */
239       memset (&conn->stats, 0, sizeof (conn->stats));
240       clock_gettime (CLOCK_REALTIME, &conn->stats.start);
241     }
242 }
243
244
245 static inline void
246 stream_test_server (vcl_test_server_conn_t * conn, int rx_bytes)
247 {
248   int client_fd = conn->fd;
249   sock_test_t test = conn->cfg.test;
250
251   if (test == SOCK_TEST_TYPE_BI)
252     (void) vcl_test_write (client_fd, conn->buf, rx_bytes, &conn->stats,
253                            conn->cfg.verbose);
254
255   if (conn->stats.rx_bytes >= conn->cfg.total_bytes)
256     {
257       clock_gettime (CLOCK_REALTIME, &conn->stats.stop);
258     }
259 }
260
261 static void
262 vcl_test_server_echo (vcl_test_server_conn_t * conn, int rx_bytes)
263 {
264   int tx_bytes, nbytes, pos;
265
266   /* If it looks vaguely like a string,
267    * make sure it's terminated
268    */
269   pos = rx_bytes < conn->buf_size ? rx_bytes : conn->buf_size - 1;
270   ((char *) conn->buf)[pos] = 0;
271   vtinf ("(fd %d): RX (%d bytes) - '%s'", conn->fd, rx_bytes, conn->buf);
272
273   if (conn->cfg.verbose)
274     vtinf ("(fd %d): Echoing back", conn->fd);
275
276   nbytes = strlen ((const char *) conn->buf) + 1;
277   tx_bytes = vcl_test_write (conn->fd, conn->buf, nbytes, &conn->stats,
278                              conn->cfg.verbose);
279   if (tx_bytes >= 0)
280     vtinf ("(fd %d): TX (%d bytes) - '%s'", conn->fd, tx_bytes, conn->buf);
281 }
282
283 static inline void
284 vcl_test_server_new_client (vcl_test_server_worker_t * wrk)
285 {
286   int client_fd;
287   vcl_test_server_conn_t *conn;
288
289   conn = conn_pool_alloc (wrk);
290   if (!conn)
291     {
292       vtwrn ("No free connections!");
293       return;
294     }
295
296   client_fd = vppcom_session_accept (wrk->listen_fd, &conn->endpt, 0);
297   if (client_fd < 0)
298     {
299       vterr ("vppcom_session_accept()", client_fd);
300       return;
301     }
302
303   vtinf ("Got a connection -- fd = %d (0x%08x)!", client_fd, client_fd);
304
305   conn->fd = client_fd;
306
307   {
308     struct epoll_event ev;
309     int rv;
310
311     ev.events = EPOLLIN;
312     ev.data.u64 = conn - wrk->conn_pool;
313     rv = vppcom_epoll_ctl (wrk->epfd, EPOLL_CTL_ADD, client_fd, &ev);
314     if (rv < 0)
315       {
316         vterr ("vppcom_epoll_ctl()", rv);
317         return;
318       }
319     wrk->nfds++;
320   }
321 }
322
323 void
324 print_usage_and_exit (void)
325 {
326   fprintf (stderr,
327            "sock_test_server [OPTIONS] <port>\n"
328            "  OPTIONS\n"
329            "  -h               Print this message and exit.\n"
330            "  -6               Use IPv6\n"
331            "  -w <num>         Number of workers\n"
332            "  -u               Use UDP transport layer\n");
333   exit (1);
334 }
335
336 static void
337 vcl_test_init_endpoint_addr (vcl_test_server_main_t * ssm)
338 {
339   struct sockaddr_storage *servaddr = &ssm->servaddr;
340   memset (servaddr, 0, sizeof (*servaddr));
341
342   if (ssm->cfg.address_ip6)
343     {
344       struct sockaddr_in6 *server_addr = (struct sockaddr_in6 *) servaddr;
345       server_addr->sin6_family = AF_INET6;
346       server_addr->sin6_addr = in6addr_any;
347       server_addr->sin6_port = htons (ssm->cfg.port);
348     }
349   else
350     {
351       struct sockaddr_in *server_addr = (struct sockaddr_in *) servaddr;
352       server_addr->sin_family = AF_INET;
353       server_addr->sin_addr.s_addr = htonl (INADDR_ANY);
354       server_addr->sin_port = htons (ssm->cfg.port);
355     }
356
357   if (ssm->cfg.address_ip6)
358     {
359       struct sockaddr_in6 *server_addr = (struct sockaddr_in6 *) servaddr;
360       ssm->cfg.endpt.is_ip4 = 0;
361       ssm->cfg.endpt.ip = (uint8_t *) & server_addr->sin6_addr;
362       ssm->cfg.endpt.port = (uint16_t) server_addr->sin6_port;
363     }
364   else
365     {
366       struct sockaddr_in *server_addr = (struct sockaddr_in *) servaddr;
367       ssm->cfg.endpt.is_ip4 = 1;
368       ssm->cfg.endpt.ip = (uint8_t *) & server_addr->sin_addr;
369       ssm->cfg.endpt.port = (uint16_t) server_addr->sin_port;
370     }
371 }
372
373 void
374 vcl_test_server_process_opts (vcl_test_server_main_t * ssm, int argc,
375                               char **argv)
376 {
377   int v, c;
378
379   ssm->cfg.proto = VPPCOM_PROTO_TCP;
380
381   opterr = 0;
382   while ((c = getopt (argc, argv, "6Dw:")) != -1)
383     switch (c)
384       {
385       case '6':
386         ssm->cfg.address_ip6 = 1;
387         break;
388
389       case 'D':
390         ssm->cfg.proto = VPPCOM_PROTO_UDP;
391         break;
392
393       case 'w':
394         v = atoi (optarg);
395         if (v > 1)
396           ssm->cfg.workers = v;
397         else
398           vtwrn ("Invalid number of workers %d", v);
399         break;
400
401       case '?':
402         switch (optopt)
403           {
404           default:
405             if (isprint (optopt))
406               fprintf (stderr, "SERVER: ERROR: Unknown "
407                        "option `-%c'.\n", optopt);
408             else
409               fprintf (stderr, "SERVER: ERROR: Unknown "
410                        "option character `\\x%x'.\n", optopt);
411           }
412         /* fall thru */
413       case 'h':
414       default:
415         print_usage_and_exit ();
416       }
417
418   if (argc < (optind + 1))
419     {
420       fprintf (stderr, "SERVER: ERROR: Insufficient number of arguments!\n");
421       print_usage_and_exit ();
422     }
423
424   if (sscanf (argv[optind], "%d", &v) == 1)
425     ssm->cfg.port = (uint16_t) v;
426   else
427     {
428       fprintf (stderr, "SERVER: ERROR: Invalid port (%s)!\n", argv[optind]);
429       print_usage_and_exit ();
430     }
431
432   vcl_test_init_endpoint_addr (ssm);
433 }
434
435 int
436 vcl_test_server_handle_cfg (vcl_test_server_worker_t * wrk,
437                             sock_test_cfg_t * rx_cfg,
438                             vcl_test_server_conn_t * conn, int rx_bytes)
439 {
440   if (rx_cfg->verbose)
441     {
442       vtinf ("(fd %d): Received a cfg msg!", conn->fd);
443       sock_test_cfg_dump (rx_cfg, 0 /* is_client */ );
444     }
445
446   if (rx_bytes != sizeof (*rx_cfg))
447     {
448       vtinf ("(fd %d): Invalid cfg msg size %d expected %lu!", conn->fd,
449              rx_bytes, sizeof (*rx_cfg));
450       conn->cfg.rxbuf_size = 0;
451       conn->cfg.num_writes = 0;
452       if (conn->cfg.verbose)
453         {
454           vtinf ("(fd %d): Replying to cfg msg", conn->fd);
455           sock_test_cfg_dump (rx_cfg, 0 /* is_client */ );
456         }
457       vcl_test_write (conn->fd, (uint8_t *) & conn->cfg,
458                       sizeof (conn->cfg), NULL, conn->cfg.verbose);
459       return -1;
460     }
461
462   switch (rx_cfg->test)
463     {
464     case SOCK_TEST_TYPE_NONE:
465     case SOCK_TEST_TYPE_ECHO:
466       sync_config_and_reply (conn, rx_cfg);
467       break;
468
469     case SOCK_TEST_TYPE_BI:
470     case SOCK_TEST_TYPE_UNI:
471       stream_test_server_start_stop (wrk, conn, rx_cfg);
472       break;
473
474     case SOCK_TEST_TYPE_EXIT:
475       vtinf ("Have a great day conn %d (closing)!", conn->fd);
476       vppcom_session_close (conn->fd);
477       conn_pool_free (conn);
478       wrk->nfds--;
479       break;
480
481     default:
482       vtwrn ("Unknown test type %d", rx_cfg->test);
483       sock_test_cfg_dump (rx_cfg, 0 /* is_client */ );
484       break;
485     }
486
487   return 0;
488 }
489
490 static void
491 vcl_test_server_worker_init (vcl_test_server_worker_t * wrk)
492 {
493   vcl_test_server_main_t *ssm = &sock_server_main;
494   struct epoll_event listen_ev;
495   int rv;
496
497   __wrk_index = wrk->wrk_index;
498
499   vtinf ("Initializing worker ...");
500
501   conn_pool_expand (wrk, SOCK_SERVER_MAX_TEST_CONN + 1);
502   if (wrk->wrk_index)
503     vppcom_worker_register ();
504
505   wrk->listen_fd = vppcom_session_create (ssm->cfg.proto,
506                                           0 /* is_nonblocking */ );
507   if (wrk->listen_fd < 0)
508     vtfail ("vppcom_session_create()", wrk->listen_fd);
509
510   rv = vppcom_session_bind (wrk->listen_fd, &ssm->cfg.endpt);
511   if (rv < 0)
512     vtfail ("vppcom_session_bind()", rv);
513
514   if (!(ssm->cfg.proto == VPPCOM_PROTO_UDP))
515     {
516       rv = vppcom_session_listen (wrk->listen_fd, 10);
517       if (rv < 0)
518         vtfail ("vppcom_session_listen()", rv);
519     }
520
521   wrk->epfd = vppcom_epoll_create ();
522   if (wrk->epfd < 0)
523     vtfail ("vppcom_epoll_create()", wrk->epfd);
524
525   listen_ev.events = EPOLLIN;
526   listen_ev.data.u32 = ~0;
527   rv = vppcom_epoll_ctl (wrk->epfd, EPOLL_CTL_ADD, wrk->listen_fd,
528                          &listen_ev);
529   if (rv < 0)
530     vtfail ("vppcom_epoll_ctl", rv);
531
532   vtinf ("Waiting for a client to connect on port %d ...", ssm->cfg.port);
533 }
534
535 static void *
536 vcl_test_server_worker_loop (void *arg)
537 {
538   vcl_test_server_main_t *ssm = &sock_server_main;
539   vcl_test_server_worker_t *wrk = arg;
540   vcl_test_server_conn_t *conn;
541   int i, rx_bytes, num_ev;
542   sock_test_cfg_t *rx_cfg;
543
544   if (wrk->wrk_index)
545     vcl_test_server_worker_init (wrk);
546
547   while (1)
548     {
549       num_ev = vppcom_epoll_wait (wrk->epfd, wrk->wait_events,
550                                   SOCK_SERVER_MAX_EPOLL_EVENTS, 60000.0);
551       if (num_ev < 0)
552         {
553           vterr ("vppcom_epoll_wait()", num_ev);
554           goto fail;
555         }
556       else if (num_ev == 0)
557         {
558           vtinf ("vppcom_epoll_wait() timeout!");
559           continue;
560         }
561       for (i = 0; i < num_ev; i++)
562         {
563           conn = &wrk->conn_pool[wrk->wait_events[i].data.u32];
564           if (wrk->wait_events[i].events & (EPOLLHUP | EPOLLRDHUP))
565             {
566               vppcom_session_close (conn->fd);
567               continue;
568             }
569           if (wrk->wait_events[i].data.u32 == ~0)
570             {
571               vcl_test_server_new_client (wrk);
572               continue;
573             }
574
575           if (EPOLLIN & wrk->wait_events[i].events)
576             {
577               rx_bytes = vcl_test_read (conn->fd, conn->buf,
578                                         conn->buf_size, &conn->stats);
579
580               if (rx_bytes <= 0)
581                 {
582                   if (errno == ECONNRESET)
583                     {
584                       vtinf ("Connection reset by remote peer.\n");
585                       goto fail;
586                     }
587                   else
588                     continue;
589                 }
590
591               rx_cfg = (sock_test_cfg_t *) conn->buf;
592               if (rx_cfg->magic == SOCK_TEST_CFG_CTRL_MAGIC)
593                 {
594                   vcl_test_server_handle_cfg (wrk, rx_cfg, conn, rx_bytes);
595                   if (!wrk->nfds)
596                     {
597                       vtinf ("All client connections closed\n");
598                       vtinf ("May the force be with you!\n");
599                       goto done;
600                     }
601                   continue;
602                 }
603               else if ((conn->cfg.test == SOCK_TEST_TYPE_UNI)
604                        || (conn->cfg.test == SOCK_TEST_TYPE_BI))
605                 {
606                   stream_test_server (conn, rx_bytes);
607                   continue;
608                 }
609               else if (isascii (conn->buf[0]))
610                 {
611                   vcl_test_server_echo (conn, rx_bytes);
612                 }
613               else
614                 {
615                   vtwrn ("FIFO not drained! extra bytes %d", rx_bytes);
616                 }
617             }
618           else
619             {
620               vtwrn ("Unhandled event");
621               goto fail;
622             }
623         }
624     }
625
626 fail:
627   ssm->worker_fails -= 1;
628
629 done:
630   vppcom_session_close (wrk->listen_fd);
631   if (wrk->conn_pool)
632     free (wrk->conn_pool);
633   ssm->active_workers -= 1;
634   return 0;
635 }
636
637 int
638 main (int argc, char **argv)
639 {
640   vcl_test_server_main_t *ssm = &sock_server_main;
641   int rv, i;
642
643   clib_mem_init_thread_safe (0, 64 << 20);
644   ssm->cfg.port = SOCK_TEST_SERVER_PORT;
645   ssm->cfg.workers = 1;
646   ssm->active_workers = 1;
647   vcl_test_server_process_opts (ssm, argc, argv);
648
649   rv = vppcom_app_create ("vcl_test_server");
650   if (rv)
651     vtfail ("vppcom_app_create()", rv);
652
653   ssm->workers = calloc (ssm->cfg.workers, sizeof (*ssm->workers));
654   vcl_test_server_worker_init (&ssm->workers[0]);
655   for (i = 1; i < ssm->cfg.workers; i++)
656     {
657       ssm->workers[i].wrk_index = i;
658       rv = pthread_create (&ssm->workers[i].thread_handle, NULL,
659                            vcl_test_server_worker_loop,
660                            (void *) &ssm->workers[i]);
661     }
662   vcl_test_server_worker_loop (&ssm->workers[0]);
663
664   while (ssm->active_workers > 0)
665     ;
666
667   vppcom_app_destroy ();
668   free (ssm->workers);
669
670   return ssm->worker_fails;
671 }
672
673 /*
674  * fd.io coding-style-patch-verification: ON
675  *
676  * Local Variables:
677  * eval: (c-set-style "gnu")
678  * End:
679  */