From 00dd74cee7ef8c1c5265daf01db13891ed68507f Mon Sep 17 00:00:00 2001 From: Florin Coras Date: Tue, 25 Jun 2019 12:55:15 -0700 Subject: hsa: move vcl test apps to hsa Type: refactor Change-Id: I352975585c1091bfc5b85d7f8fe985f9059820a7 Signed-off-by: Florin Coras --- src/plugins/hs_apps/CMakeLists.txt | 37 +- src/plugins/hs_apps/quic_echo.c | 1841 ---------------------------- src/plugins/hs_apps/sapi/quic_echo.c | 1841 ++++++++++++++++++++++++++++ src/plugins/hs_apps/sapi/tcp_echo.c | 1414 +++++++++++++++++++++ src/plugins/hs_apps/sapi/udp_echo.c | 1256 +++++++++++++++++++ src/plugins/hs_apps/tcp_echo.c | 1414 --------------------- src/plugins/hs_apps/udp_echo.c | 1256 ------------------- src/plugins/hs_apps/vcl/sock_test.h | 122 ++ src/plugins/hs_apps/vcl/sock_test_client.c | 1277 +++++++++++++++++++ src/plugins/hs_apps/vcl/sock_test_server.c | 1015 +++++++++++++++ src/plugins/hs_apps/vcl/vcl_test.h | 538 ++++++++ src/plugins/hs_apps/vcl/vcl_test_client.c | 1097 +++++++++++++++++ src/plugins/hs_apps/vcl/vcl_test_server.c | 743 +++++++++++ 13 files changed, 9334 insertions(+), 4517 deletions(-) delete mode 100644 src/plugins/hs_apps/quic_echo.c create mode 100644 src/plugins/hs_apps/sapi/quic_echo.c create mode 100644 src/plugins/hs_apps/sapi/tcp_echo.c create mode 100644 src/plugins/hs_apps/sapi/udp_echo.c delete mode 100644 src/plugins/hs_apps/tcp_echo.c delete mode 100644 src/plugins/hs_apps/udp_echo.c create mode 100644 src/plugins/hs_apps/vcl/sock_test.h create mode 100644 src/plugins/hs_apps/vcl/sock_test_client.c create mode 100644 src/plugins/hs_apps/vcl/sock_test_server.c create mode 100644 src/plugins/hs_apps/vcl/vcl_test.h create mode 100644 src/plugins/hs_apps/vcl/vcl_test_client.c create mode 100644 src/plugins/hs_apps/vcl/vcl_test_server.c (limited to 'src/plugins/hs_apps') diff --git a/src/plugins/hs_apps/CMakeLists.txt b/src/plugins/hs_apps/CMakeLists.txt index e7885c3d1bf..bf1f49cfa42 100644 --- a/src/plugins/hs_apps/CMakeLists.txt +++ b/src/plugins/hs_apps/CMakeLists.txt @@ -11,6 +11,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +############################################################################## +# vpp builtin hs apps +############################################################################## add_vpp_plugin(hs_apps SOURCES echo_client.c @@ -20,24 +23,46 @@ add_vpp_plugin(hs_apps proxy.c ) -option(VPP_BUILD_SESSION_ECHO_APPS "Build session echo apps." ON) -if(VPP_BUILD_SESSION_ECHO_APPS) +############################################################################## +# vpp external hs apps that use the "raw" session layer api +############################################################################## +option(VPP_BUILD_HS_SAPI_APPS "Build hs apps that use the session api." ON) +if(VPP_BUILD_HS_SAPI_APPS) add_vpp_executable(tcp_echo - SOURCES tcp_echo.c + SOURCES sapi/tcp_echo.c LINK_LIBRARIES vlibmemoryclient svm vppinfra pthread m rt DEPENDS api_headers NO_INSTALL ) add_vpp_executable(quic_echo - SOURCES quic_echo.c + SOURCES sapi/quic_echo.c LINK_LIBRARIES vlibmemoryclient svm vppinfra pthread m rt DEPENDS api_headers NO_INSTALL ) add_vpp_executable(udp_echo - SOURCES udp_echo.c + SOURCES sapi/udp_echo.c LINK_LIBRARIES vlibmemoryclient svm vppinfra pthread m rt DEPENDS api_headers NO_INSTALL ) -endif(VPP_BUILD_SESSION_ECHO_APPS) +endif(VPP_BUILD_HS_SAPI_APPS) + +############################################################################## +# vcl tests +############################################################################## +option(VPP_BUILD_VCL_TESTS "Build vcl tests." ON) +if(VPP_BUILD_VCL_TESTS) + foreach(test + vcl_test_server + vcl_test_client + sock_test_server + sock_test_client + ) + add_vpp_executable(${test} + SOURCES "vcl/${test}.c" + LINK_LIBRARIES vppcom pthread + NO_INSTALL + ) + endforeach() +endif(VPP_BUILD_VCL_TESTS) diff --git a/src/plugins/hs_apps/quic_echo.c b/src/plugins/hs_apps/quic_echo.c deleted file mode 100644 index a62af642b2f..00000000000 --- a/src/plugins/hs_apps/quic_echo.c +++ /dev/null @@ -1,1841 +0,0 @@ -/* - * Copyright (c) 2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include -#include - -#include -#include - -#define vl_typedefs /* define message structures */ -#include -#undef vl_typedefs - -/* declare message handlers for each api */ - -#define vl_endianfun /* define message structures */ -#include -#undef vl_endianfun - -/* instantiate all the print functions we know about */ -#define vl_print(handle, ...) -#define vl_printfun -#include -#undef vl_printfun - -#define QUIC_ECHO_DBG 0 -#define DBG(_fmt, _args...) \ - if (QUIC_ECHO_DBG) \ - clib_warning (_fmt, ##_args) - -typedef struct -{ - CLIB_CACHE_LINE_ALIGN_MARK (cacheline0); -#define _(type, name) type name; - foreach_app_session_field -#undef _ - u64 vpp_session_handle; - u64 bytes_sent; - u64 bytes_to_send; - volatile u64 bytes_received; - volatile u64 bytes_to_receive; - f64 start; -} echo_session_t; - -typedef enum -{ - STATE_START, - STATE_ATTACHED, - STATE_LISTEN, - STATE_READY, - STATE_DISCONNECTING, - STATE_FAILED, - STATE_DETACHED -} connection_state_t; - -typedef enum -{ - ECHO_EVT_START, /* app starts */ - ECHO_EVT_FIRST_QCONNECT, /* First connect Quic session sent */ - ECHO_EVT_LAST_QCONNECTED, /* All Quic session are connected */ - ECHO_EVT_FIRST_SCONNECT, /* First connect Stream session sent */ - ECHO_EVT_LAST_SCONNECTED, /* All Stream session are connected */ - ECHO_EVT_LAST_BYTE, /* Last byte received */ - ECHO_EVT_EXIT, /* app exits */ -} echo_test_evt_t; - -enum quic_session_type_t -{ - QUIC_SESSION_TYPE_QUIC = 0, - QUIC_SESSION_TYPE_STREAM = 1, - QUIC_SESSION_TYPE_LISTEN = INT32_MAX, -}; - -typedef struct _quic_echo_cb_vft -{ - void (*quic_connected_cb) (session_connected_msg_t * mp, u32 session_index); - void (*client_stream_connected_cb) (session_connected_msg_t * mp, - u32 session_index); - void (*server_stream_connected_cb) (session_connected_msg_t * mp, - u32 session_index); - void (*quic_accepted_cb) (session_accepted_msg_t * mp, u32 session_index); - void (*client_stream_accepted_cb) (session_accepted_msg_t * mp, - u32 session_index); - void (*server_stream_accepted_cb) (session_accepted_msg_t * mp, - u32 session_index); -} quic_echo_cb_vft_t; - - -typedef enum -{ - RETURN_PACKETS_NOTEST, - RETURN_PACKETS_LOG_WRONG, - RETURN_PACKETS_ASSERT, -} test_return_packets_t; - -typedef struct -{ - /* vpe input queue */ - svm_queue_t *vl_input_queue; - - /* API client handle */ - u32 my_client_index; - - /* The URI we're playing with */ - u8 *uri; - - /* Session pool */ - echo_session_t *sessions; - - /* Hash table for disconnect processing */ - uword *session_index_by_vpp_handles; - /* Handle of vpp listener session */ - u64 listener_handle; - - /* Hash table for shared segment_names */ - uword *shared_segment_handles; - clib_spinlock_t segment_handles_lock; - - /* intermediate rx buffer */ - u8 *rx_buf; - - int i_am_master; - - /* drop all packets */ - int no_return; - - /* Our event queue */ - svm_msg_q_t *our_event_queue; - - u8 *socket_name; - - pid_t my_pid; - - /* For deadman timers */ - clib_time_t clib_time; - - /* State of the connection, shared between msg RX thread and main thread */ - volatile connection_state_t state; - - /* Signal variables */ - volatile int time_to_stop; - - /* VNET_API_ERROR_FOO -> "Foo" hash table */ - uword *error_string_by_error_number; - - u8 *connect_test_data; - pthread_t *client_thread_handles; - u32 *thread_args; - u8 test_return_packets; - u64 bytes_to_send; - u64 bytes_to_receive; - u32 fifo_size; - - u8 *appns_id; - u64 appns_flags; - u64 appns_secret; - - u32 n_clients; /* Target number of QUIC sessions */ - u32 n_stream_clients; /* Target Number of STREAM sessions per QUIC session */ - volatile u32 n_quic_clients_connected; /* Number of connected QUIC sessions */ - volatile u32 n_clients_connected; /* Number of STREAM sessions connected */ - - u64 tx_total; - u64 rx_total; - - /* Event based timing : start & end depend on CLI specified events */ - u8 first_sconnect_sent; /* Sent the first Stream session connect ? */ - f64 start_time; - f64 end_time; - u8 timing_start_event; - u8 timing_end_event; - - /* cb vft for QUIC scenarios */ - quic_echo_cb_vft_t cb_vft; - - /** Flag that decides if socket, instead of svm, api is used to connect to - * vpp. If sock api is used, shm binary api is subsequently bootstrapped - * and all other messages are exchanged using shm IPC. */ - u8 use_sock_api; - - /* Limit the number of incorrect data messages */ - int max_test_msg; - - fifo_segment_main_t segment_main; -} echo_main_t; - -echo_main_t echo_main; - -#if CLIB_DEBUG > 0 -#define NITER 10000 -#else -#define NITER 4000000 -#endif - -#if CLIB_DEBUG > 0 -#define TIMEOUT 10.0 -#else -#define TIMEOUT 10.0 -#endif - -u8 * -format_quic_echo_state (u8 * s, va_list * args) -{ - u32 state = va_arg (*args, u32); - if (state == STATE_START) - return format (s, "STATE_START"); - if (state == STATE_ATTACHED) - return format (s, "STATE_ATTACHED"); - if (state == STATE_LISTEN) - return format (s, "STATE_LISTEN"); - if (state == STATE_READY) - return format (s, "STATE_READY"); - if (state == STATE_DISCONNECTING) - return format (s, "STATE_DISCONNECTING"); - if (state == STATE_FAILED) - return format (s, "STATE_FAILED"); - if (state == STATE_DETACHED) - return format (s, "STATE_DETACHED"); - else - return format (s, "unknown state"); -} - -static u8 * -format_api_error (u8 * s, va_list * args) -{ - echo_main_t *em = &echo_main; - i32 error = va_arg (*args, u32); - uword *p; - - p = hash_get (em->error_string_by_error_number, -error); - - if (p) - s = format (s, "%s", p[0]); - else - s = format (s, "%d", error); - return s; -} - -static void -quic_echo_notify_event (echo_main_t * em, echo_test_evt_t e) -{ - if (em->timing_start_event == e) - em->start_time = clib_time_now (&em->clib_time); - else if (em->timing_end_event == e) - em->end_time = clib_time_now (&em->clib_time); -} - -static uword -echo_unformat_timing_event (unformat_input_t * input, va_list * args) -{ - echo_test_evt_t *a = va_arg (*args, echo_test_evt_t *); - if (unformat (input, "start")) - *a = ECHO_EVT_START; - else if (unformat (input, "qconnect")) - *a = ECHO_EVT_FIRST_QCONNECT; - else if (unformat (input, "qconnected")) - *a = ECHO_EVT_LAST_QCONNECTED; - else if (unformat (input, "sconnect")) - *a = ECHO_EVT_FIRST_SCONNECT; - else if (unformat (input, "sconnected")) - *a = ECHO_EVT_LAST_SCONNECTED; - else if (unformat (input, "lastbyte")) - *a = ECHO_EVT_LAST_BYTE; - else if (unformat (input, "exit")) - *a = ECHO_EVT_EXIT; - else - return 0; - return 1; -} - -u8 * -echo_format_timing_event (u8 * s, va_list * args) -{ - u32 timing_event = va_arg (*args, u32); - if (timing_event == ECHO_EVT_START) - return format (s, "start"); - if (timing_event == ECHO_EVT_FIRST_QCONNECT) - return format (s, "qconnect"); - if (timing_event == ECHO_EVT_LAST_QCONNECTED) - return format (s, "qconnected"); - if (timing_event == ECHO_EVT_FIRST_SCONNECT) - return format (s, "sconnect"); - if (timing_event == ECHO_EVT_LAST_SCONNECTED) - return format (s, "sconnected"); - if (timing_event == ECHO_EVT_LAST_BYTE) - return format (s, "lastbyte"); - if (timing_event == ECHO_EVT_EXIT) - return format (s, "exit"); - else - return format (s, "unknown timing event"); -} - -static void -init_error_string_table (echo_main_t * em) -{ - em->error_string_by_error_number = hash_create (0, sizeof (uword)); - -#define _(n,v,s) hash_set (em->error_string_by_error_number, -v, s); - foreach_vnet_api_error; -#undef _ - - hash_set (em->error_string_by_error_number, 99, "Misc"); -} - -static void handle_mq_event (echo_main_t * em, session_event_t * e, - int handle_rx); -static void echo_handle_rx (echo_main_t * em, session_event_t * e); - -static int -wait_for_segment_allocation (u64 segment_handle) -{ - echo_main_t *em = &echo_main; - f64 timeout; - timeout = clib_time_now (&em->clib_time) + TIMEOUT; - uword *segment_present; - DBG ("Waiting for segment %lx...", segment_handle); - while (clib_time_now (&em->clib_time) < timeout) - { - clib_spinlock_lock (&em->segment_handles_lock); - segment_present = hash_get (em->shared_segment_handles, segment_handle); - clib_spinlock_unlock (&em->segment_handles_lock); - if (segment_present != 0) - return 0; - if (em->time_to_stop == 1) - return 0; - } - DBG ("timeout waiting for segment_allocation %lx", segment_handle); - return -1; -} - -static int -wait_for_disconnected_sessions (echo_main_t * em) -{ - f64 timeout; - timeout = clib_time_now (&em->clib_time) + TIMEOUT; - while (clib_time_now (&em->clib_time) < timeout) - { - if (hash_elts (em->session_index_by_vpp_handles) == 0) - return 0; - } - DBG ("timeout waiting for disconnected_sessions"); - return -1; -} - -static int -wait_for_state_change (echo_main_t * em, connection_state_t state, - f64 timeout) -{ - svm_msg_q_msg_t msg; - session_event_t *e; - f64 end_time = clib_time_now (&em->clib_time) + timeout; - - while (!timeout || clib_time_now (&em->clib_time) < end_time) - { - if (em->state == state) - return 0; - if (em->state == STATE_FAILED) - return -1; - if (em->time_to_stop == 1) - return 0; - if (!em->our_event_queue || em->state < STATE_ATTACHED) - continue; - - if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_NOWAIT, 0)) - continue; - e = svm_msg_q_msg_data (em->our_event_queue, &msg); - handle_mq_event (em, e, 0 /* handle_rx */ ); - svm_msg_q_free_msg (em->our_event_queue, &msg); - } - clib_warning ("timeout waiting for state %U", format_quic_echo_state, - state); - return -1; -} - -static void -notify_rx_data_to_vpp (echo_session_t * s) -{ - svm_fifo_t *f = s->tx_fifo; - return; /* FOR NOW */ - if (svm_fifo_set_event (f)) - { - DBG ("did send event"); - app_send_io_evt_to_vpp (s->vpp_evt_q, f->master_session_index, - SESSION_IO_EVT_TX, 0 /* noblock */ ); - } -} - -void -application_send_attach (echo_main_t * em) -{ - vl_api_application_attach_t *bmp; - vl_api_application_tls_cert_add_t *cert_mp; - vl_api_application_tls_key_add_t *key_mp; - - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH); - bmp->client_index = em->my_client_index; - bmp->context = ntohl (0xfeedface); - bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ACCEPT_REDIRECT; - bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_ADD_SEGMENT; - bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 16; - bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = em->fifo_size; - bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = em->fifo_size; - bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20; - bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20; - bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 256; - if (em->appns_id) - { - bmp->namespace_id_len = vec_len (em->appns_id); - clib_memcpy_fast (bmp->namespace_id, em->appns_id, - bmp->namespace_id_len); - bmp->options[APP_OPTIONS_FLAGS] |= em->appns_flags; - bmp->options[APP_OPTIONS_NAMESPACE_SECRET] = em->appns_secret; - } - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); - - cert_mp = vl_msg_api_alloc (sizeof (*cert_mp) + test_srv_crt_rsa_len); - clib_memset (cert_mp, 0, sizeof (*cert_mp)); - cert_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_CERT_ADD); - cert_mp->client_index = em->my_client_index; - cert_mp->context = ntohl (0xfeedface); - cert_mp->cert_len = clib_host_to_net_u16 (test_srv_crt_rsa_len); - clib_memcpy_fast (cert_mp->cert, test_srv_crt_rsa, test_srv_crt_rsa_len); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cert_mp); - - key_mp = vl_msg_api_alloc (sizeof (*key_mp) + test_srv_key_rsa_len); - clib_memset (key_mp, 0, sizeof (*key_mp) + test_srv_key_rsa_len); - key_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_KEY_ADD); - key_mp->client_index = em->my_client_index; - key_mp->context = ntohl (0xfeedface); - key_mp->key_len = clib_host_to_net_u16 (test_srv_key_rsa_len); - clib_memcpy_fast (key_mp->key, test_srv_key_rsa, test_srv_key_rsa_len); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & key_mp); -} - -static int -application_attach (echo_main_t * em) -{ - application_send_attach (em); - return wait_for_state_change (em, STATE_ATTACHED, TIMEOUT); -} - -void -application_detach (echo_main_t * em) -{ - vl_api_application_detach_t *bmp; - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH); - bmp->client_index = em->my_client_index; - bmp->context = ntohl (0xfeedface); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); - - DBG ("%s", "Sent detach"); -} - -static int -ssvm_segment_attach (char *name, ssvm_segment_type_t type, int fd) -{ - fifo_segment_create_args_t _a, *a = &_a; - fifo_segment_main_t *sm = &echo_main.segment_main; - int rv; - - clib_memset (a, 0, sizeof (*a)); - a->segment_name = (char *) name; - a->segment_type = type; - - if (type == SSVM_SEGMENT_MEMFD) - a->memfd_fd = fd; - - if ((rv = fifo_segment_attach (sm, a))) - { - clib_warning ("svm_fifo_segment_attach ('%s') failed", name); - return rv; - } - vec_reset_length (a->new_segment_indices); - return 0; -} - -static void -vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t * - mp) -{ - echo_main_t *em = &echo_main; - int *fds = 0; - u32 n_fds = 0; - u64 segment_handle; - segment_handle = clib_net_to_host_u64 (mp->segment_handle); - DBG ("Attached returned app %u", htons (mp->app_index)); - - if (mp->retval) - { - clib_warning ("attach failed: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - goto failed; - } - - if (mp->segment_name_length == 0) - { - clib_warning ("segment_name_length zero"); - goto failed; - } - - ASSERT (mp->app_event_queue_address); - em->our_event_queue = uword_to_pointer (mp->app_event_queue_address, - svm_msg_q_t *); - - if (mp->n_fds) - { - vec_validate (fds, mp->n_fds); - vl_socket_client_recv_fd_msg (fds, mp->n_fds, 5); - - if (mp->fd_flags & SESSION_FD_F_VPP_MQ_SEGMENT) - if (ssvm_segment_attach (0, SSVM_SEGMENT_MEMFD, fds[n_fds++])) - goto failed; - - if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT) - if (ssvm_segment_attach ((char *) mp->segment_name, - SSVM_SEGMENT_MEMFD, fds[n_fds++])) - goto failed; - - if (mp->fd_flags & SESSION_FD_F_MQ_EVENTFD) - svm_msg_q_set_consumer_eventfd (em->our_event_queue, fds[n_fds++]); - - vec_free (fds); - } - else - { - if (ssvm_segment_attach ((char *) mp->segment_name, SSVM_SEGMENT_SHM, - -1)) - goto failed; - } - clib_spinlock_lock (&em->segment_handles_lock); - hash_set (em->shared_segment_handles, segment_handle, 1); - clib_spinlock_unlock (&em->segment_handles_lock); - DBG ("Mapped new segment %lx", segment_handle); - - em->state = STATE_ATTACHED; - return; -failed: - em->state = STATE_FAILED; - return; -} - -static void -vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t * - mp) -{ - if (mp->retval) - clib_warning ("detach returned with err: %d", mp->retval); - echo_main.state = STATE_DETACHED; -} - -static void -stop_signal (int signum) -{ - echo_main_t *um = &echo_main; - um->time_to_stop = 1; -} - -static clib_error_t * -setup_signal_handlers (void) -{ - signal (SIGINT, stop_signal); - signal (SIGQUIT, stop_signal); - signal (SIGTERM, stop_signal); - return 0; -} - -int -connect_to_vpp (char *name) -{ - echo_main_t *em = &echo_main; - api_main_t *am = &api_main; - - if (em->use_sock_api) - { - if (vl_socket_client_connect ((char *) em->socket_name, name, - 0 /* default rx, tx buffer */ )) - { - clib_warning ("socket connect failed"); - return -1; - } - - if (vl_socket_client_init_shm (0, 1 /* want_pthread */ )) - { - clib_warning ("init shm api failed"); - return -1; - } - } - else - { - if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0) - { - clib_warning ("shmem connect failed"); - return -1; - } - } - em->vl_input_queue = am->shmem_hdr->vl_input_queue; - em->my_client_index = am->my_client_index; - return 0; -} - -void -disconnect_from_vpp (echo_main_t * em) -{ - if (em->use_sock_api) - vl_socket_client_disconnect (); - else - vl_client_disconnect_from_vlib (); -} - -static void -vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp) -{ - fifo_segment_main_t *sm = &echo_main.segment_main; - fifo_segment_create_args_t _a, *a = &_a; - echo_main_t *em = &echo_main; - int rv; - int *fds = 0; - u64 segment_handle; - segment_handle = clib_net_to_host_u64 (mp->segment_handle); - - if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT) - { - vec_validate (fds, 1); - vl_socket_client_recv_fd_msg (fds, 1, 5); - if (ssvm_segment_attach - ((char *) mp->segment_name, SSVM_SEGMENT_MEMFD, fds[0])) - clib_warning - ("svm_fifo_segment_attach ('%s') failed on SSVM_SEGMENT_MEMFD", - mp->segment_name); - clib_spinlock_lock (&em->segment_handles_lock); - hash_set (em->shared_segment_handles, segment_handle, 1); - clib_spinlock_unlock (&em->segment_handles_lock); - vec_free (fds); - DBG ("Mapped new segment %lx", segment_handle); - return; - } - - clib_memset (a, 0, sizeof (*a)); - a->segment_name = (char *) mp->segment_name; - a->segment_size = mp->segment_size; - /* Attach to the segment vpp created */ - rv = fifo_segment_attach (sm, a); - if (rv) - { - clib_warning ("svm_fifo_segment_attach ('%s') failed", - mp->segment_name); - return; - } - clib_spinlock_lock (&em->segment_handles_lock); - hash_set (em->shared_segment_handles, mp->segment_name, 1); - clib_spinlock_unlock (&em->segment_handles_lock); - clib_warning ("Mapped new segment '%s' size %d", mp->segment_name, - mp->segment_size); -} - -static void -session_print_stats (echo_main_t * em, echo_session_t * session) -{ - f64 deltat = clib_time_now (&em->clib_time) - session->start; - fformat (stdout, "Session %x done in %.6fs RX[%.4f] TX[%.4f] Gbit/s\n", - session->session_index, deltat, - (session->bytes_received * 8.0) / deltat / 1e9, - (session->bytes_sent * 8.0) / deltat / 1e9); -} - -static void -print_global_stats (echo_main_t * em) -{ - f64 deltat = em->end_time - em->start_time; - u8 *s = format (0, "%U:%U", - echo_format_timing_event, em->timing_start_event, - echo_format_timing_event, em->timing_end_event); - fformat (stdout, "Timinig %s\n", s); - fformat (stdout, "-------- TX --------\n"); - fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds\n", - em->tx_total, em->tx_total / (1ULL << 20), - em->tx_total / (1ULL << 30), deltat); - fformat (stdout, "%.4f Gbit/second\n", (em->tx_total * 8.0) / deltat / 1e9); - fformat (stdout, "-------- RX --------\n"); - fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds\n", - em->rx_total, em->rx_total / (1ULL << 20), - em->rx_total / (1ULL << 30), deltat); - fformat (stdout, "%.4f Gbit/second\n", (em->rx_total * 8.0) / deltat / 1e9); - fformat (stdout, "--------------------\n"); -} - - -static void -test_recv_bytes (echo_main_t * em, echo_session_t * s, u8 * rx_buf, - u32 n_read) -{ - int i; - u8 expected; - for (i = 0; i < n_read; i++) - { - expected = (s->bytes_received + i) & 0xff; - if (rx_buf[i] != expected && em->max_test_msg > 0) - { - clib_warning - ("Session[%lx][0x%lx] byte[%lld], got 0x%x but expected 0x%x", - s->session_index, s->vpp_session_handle, s->bytes_received + i, - rx_buf[i], expected); - em->max_test_msg--; - if (em->max_test_msg == 0) - clib_warning ("Too many errors, hiding next ones"); - if (em->test_return_packets == RETURN_PACKETS_ASSERT) - ASSERT (0); - } - } -} - -static void -recv_data_chunk (echo_main_t * em, echo_session_t * s, u8 * rx_buf) -{ - int n_to_read, n_read; - - n_to_read = svm_fifo_max_dequeue (s->rx_fifo); - if (!n_to_read) - return; - - do - { - n_read = - app_recv_stream ((app_session_t *) s, rx_buf, vec_len (rx_buf)); - if (n_read <= 0) - break; - notify_rx_data_to_vpp (s); - if (em->test_return_packets) - test_recv_bytes (em, s, rx_buf, n_read); - - ASSERT (s->bytes_to_receive >= n_read); - n_to_read -= n_read; - s->bytes_received += n_read; - s->bytes_to_receive -= n_read; - } - while (n_to_read > 0); -} - -static void -send_data_chunk (echo_main_t * em, echo_session_t * s) -{ - u64 test_buf_len, bytes_this_chunk, test_buf_offset; - u8 *test_data = em->connect_test_data; - int n_sent; - - test_buf_len = vec_len (test_data); - test_buf_offset = s->bytes_sent % test_buf_len; - bytes_this_chunk = clib_min (test_buf_len - test_buf_offset, - s->bytes_to_send); - - n_sent = app_send_stream ((app_session_t *) s, test_data + test_buf_offset, - bytes_this_chunk, 0); - - if (n_sent > 0) - { - s->bytes_to_send -= n_sent; - s->bytes_sent += n_sent; - } -} - -/* - * Rx/Tx polling thread per connection - */ -static void * -client_thread_fn (void *arg) -{ - echo_main_t *em = &echo_main; - u8 *rx_buf = 0; - u32 session_index = *(u32 *) arg; - echo_session_t *s; - - vec_validate (rx_buf, 1 << 20); - - while (!em->time_to_stop && em->state != STATE_READY) - ; - - s = pool_elt_at_index (em->sessions, session_index); - while (!em->time_to_stop) - { - send_data_chunk (em, s); - recv_data_chunk (em, s, rx_buf); - if (!s->bytes_to_send && !s->bytes_to_receive) - break; - } - - DBG ("[%lu/%lu] -> S(%x) -> [%lu/%lu]", - s->bytes_received, s->bytes_received + s->bytes_to_receive, - session_index, s->bytes_sent, s->bytes_sent + s->bytes_to_send); - em->tx_total += s->bytes_sent; - em->rx_total += s->bytes_received; - em->n_clients_connected--; - - if (em->n_clients_connected == 0) - quic_echo_notify_event (em, ECHO_EVT_LAST_BYTE); - - pthread_exit (0); -} - -static void -echo_send_connect (echo_main_t * em, u8 * uri, u32 opaque) -{ - vl_api_connect_uri_t *cmp; - cmp = vl_msg_api_alloc (sizeof (*cmp)); - clib_memset (cmp, 0, sizeof (*cmp)); - - cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI); - cmp->client_index = em->my_client_index; - cmp->context = ntohl (opaque); - memcpy (cmp->uri, uri, vec_len (uri)); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cmp); -} - -static void -client_disconnect_session (echo_main_t * em, echo_session_t * s) -{ - vl_api_disconnect_session_t *dmp; - dmp = vl_msg_api_alloc (sizeof (*dmp)); - clib_memset (dmp, 0, sizeof (*dmp)); - dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION); - dmp->client_index = em->my_client_index; - dmp->handle = s->vpp_session_handle; - DBG ("Sending Session disonnect handle %lu", dmp->handle); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & dmp); - pool_put (em->sessions, s); - clib_memset (s, 0xfe, sizeof (*s)); -} - -static void -session_bound_handler (session_bound_msg_t * mp) -{ - echo_main_t *em = &echo_main; - - if (mp->retval) - { - clib_warning ("bind failed: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - em->state = STATE_FAILED; - return; - } - - clib_warning ("listening on %U:%u", format_ip46_address, mp->lcl_ip, - mp->lcl_is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6, - clib_net_to_host_u16 (mp->lcl_port)); - em->listener_handle = mp->handle; - em->state = STATE_LISTEN; -} - -static void -session_accepted_handler (session_accepted_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - session_accepted_reply_msg_t *rmp; - svm_fifo_t *rx_fifo, *tx_fifo; - echo_main_t *em = &echo_main; - echo_session_t *session; - u32 session_index; - - /* Allocate local session and set it up */ - pool_get (em->sessions, session); - session_index = session - em->sessions; - - if (wait_for_segment_allocation (mp->segment_handle)) - return; - - rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); - rx_fifo->client_session_index = session_index; - tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); - tx_fifo->client_session_index = session_index; - - session->rx_fifo = rx_fifo; - session->tx_fifo = tx_fifo; - session->session_index = session_index; - session->vpp_session_handle = mp->handle; - session->start = clib_time_now (&em->clib_time); - session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, - svm_msg_q_t *); - - /* Add it to lookup table */ - DBG ("Accepted session handle %lx, Listener %lx idx %lu", mp->handle, - mp->listener_handle, session_index); - hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); - - app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, - SESSION_CTRL_EVT_ACCEPTED_REPLY); - rmp = (session_accepted_reply_msg_t *) app_evt->evt->data; - rmp->handle = mp->handle; - rmp->context = mp->context; - app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); - - DBG ("SSession handle is %lu", mp->handle); - if (mp->listener_handle == em->listener_handle) - { - if (em->cb_vft.quic_accepted_cb) - em->cb_vft.quic_accepted_cb (mp, session_index); - em->n_quic_clients_connected++; - } - else if (em->i_am_master) - { - if (em->cb_vft.server_stream_accepted_cb) - em->cb_vft.server_stream_accepted_cb (mp, session_index); - em->n_clients_connected++; - } - else - { - if (em->cb_vft.client_stream_accepted_cb) - em->cb_vft.client_stream_accepted_cb (mp, session_index); - em->n_clients_connected++; - } - - if (em->n_clients_connected == em->n_clients * em->n_stream_clients) - { - em->state = STATE_READY; - quic_echo_notify_event (em, ECHO_EVT_LAST_SCONNECTED); - } - if (em->n_quic_clients_connected == em->n_clients) - quic_echo_notify_event (em, ECHO_EVT_LAST_QCONNECTED); -} - -static void -session_connected_handler (session_connected_msg_t * mp) -{ - echo_main_t *em = &echo_main; - echo_session_t *session; - u32 session_index; - svm_fifo_t *rx_fifo, *tx_fifo; - - if (mp->retval) - { - clib_warning ("connection failed with code: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - em->state = STATE_FAILED; - return; - } - - pool_get (em->sessions, session); - clib_memset (session, 0, sizeof (*session)); - session_index = session - em->sessions; - DBG ("CONNECTED session[%lx][0x%lx]", session_index, mp->handle); - - if (wait_for_segment_allocation (mp->segment_handle)) - return; - - rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); - rx_fifo->client_session_index = session_index; - tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); - tx_fifo->client_session_index = session_index; - - session->rx_fifo = rx_fifo; - session->tx_fifo = tx_fifo; - session->vpp_session_handle = mp->handle; - session->session_index = session_index; - session->start = clib_time_now (&em->clib_time); - session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, - svm_msg_q_t *); - - DBG ("Connected session handle %lx, idx %lu RX[%lx] TX[%lx]", mp->handle, - session_index, rx_fifo, tx_fifo); - hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); - - if (mp->context == QUIC_SESSION_TYPE_QUIC) - { - if (em->cb_vft.quic_connected_cb) - em->cb_vft.quic_connected_cb (mp, session_index); - em->n_quic_clients_connected++; - } - else if (em->i_am_master) - { - if (em->cb_vft.server_stream_connected_cb) - em->cb_vft.server_stream_connected_cb (mp, session_index); - em->n_clients_connected++; - } - else - { - if (em->cb_vft.client_stream_connected_cb) - em->cb_vft.client_stream_connected_cb (mp, session_index); - em->n_clients_connected++; - } - - if (em->n_clients_connected == em->n_clients * em->n_stream_clients) - { - em->state = STATE_READY; - quic_echo_notify_event (em, ECHO_EVT_LAST_SCONNECTED); - } - if (em->n_quic_clients_connected == em->n_clients) - quic_echo_notify_event (em, ECHO_EVT_LAST_QCONNECTED); -} - -/* - * - * ECHO Callback definitions - * - */ - - -static void -echo_on_connected_connect (session_connected_msg_t * mp, u32 session_index) -{ - echo_main_t *em = &echo_main; - u8 *uri = format (0, "QUIC://session/%lu", mp->handle); - int i; - - if (!em->first_sconnect_sent) - { - em->first_sconnect_sent = 1; - quic_echo_notify_event (em, ECHO_EVT_FIRST_SCONNECT); - } - for (i = 0; i < em->n_stream_clients; i++) - { - DBG ("CONNECT : new QUIC stream #%d: %s", i, uri); - echo_send_connect (em, uri, QUIC_SESSION_TYPE_STREAM); - } - - clib_warning ("session %u (0x%llx) connected with local ip %U port %d", - session_index, mp->handle, format_ip46_address, &mp->lcl.ip, - mp->lcl.is_ip4, clib_net_to_host_u16 (mp->lcl.port)); -} - -static void -echo_on_connected_send (session_connected_msg_t * mp, u32 session_index) -{ - echo_main_t *em = &echo_main; - int rv; - echo_session_t *session; - - DBG ("Stream Session Connected"); - - session = pool_elt_at_index (em->sessions, session_index); - session->bytes_to_send = em->bytes_to_send; - session->bytes_to_receive = em->bytes_to_receive; - - /* - * Start RX thread - */ - em->thread_args[em->n_clients_connected] = session_index; - rv = pthread_create (&em->client_thread_handles[em->n_clients_connected], - NULL /*attr */ , client_thread_fn, - (void *) &em->thread_args[em->n_clients_connected]); - if (rv) - { - clib_warning ("pthread_create returned %d", rv); - return; - } -} - -static void -echo_on_connected_error (session_connected_msg_t * mp, u32 session_index) -{ - clib_warning ("Got a wrong connected on session %u [%lx]", session_index, - mp->handle); -} - -static void -echo_on_accept_recv (session_accepted_msg_t * mp, u32 session_index) -{ - echo_main_t *em = &echo_main; - int rv; - echo_session_t *session; - - session = pool_elt_at_index (em->sessions, session_index); - session->bytes_to_send = em->bytes_to_send; - session->bytes_to_receive = em->bytes_to_receive; - - DBG ("Stream session accepted 0x%lx, expecting %lu bytes", - session->vpp_session_handle, session->bytes_to_receive); - - /* - * Start RX thread - */ - em->thread_args[em->n_clients_connected] = session_index; - rv = pthread_create (&em->client_thread_handles[em->n_clients_connected], - NULL /*attr */ , client_thread_fn, - (void *) &em->thread_args[em->n_clients_connected]); - if (rv) - { - clib_warning ("pthread_create returned %d", rv); - return; - } - -} - -static void -echo_on_accept_connect (session_accepted_msg_t * mp, u32 session_index) -{ - echo_main_t *em = &echo_main; - DBG ("Accept on QSession index %u", mp->handle); - u8 *uri = format (0, "QUIC://session/%lu", mp->handle); - u32 i; - - if (!em->first_sconnect_sent) - { - em->first_sconnect_sent = 1; - quic_echo_notify_event (em, ECHO_EVT_FIRST_SCONNECT); - } - for (i = 0; i < em->n_stream_clients; i++) - { - DBG ("ACCEPT : new QUIC stream #%d: %s", i, uri); - echo_send_connect (em, uri, QUIC_SESSION_TYPE_STREAM); - } -} - -static void -echo_on_accept_error (session_accepted_msg_t * mp, u32 session_index) -{ - clib_warning ("Got a wrong accept on session %u [%lx]", session_index, - mp->handle); -} - -static void -echo_on_accept_log_ip (session_accepted_msg_t * mp, u32 session_index) -{ - u8 *ip_str; - ip_str = format (0, "%U", format_ip46_address, &mp->rmt.ip, mp->rmt.is_ip4); - clib_warning ("Accepted session from: %s:%d", ip_str, - clib_net_to_host_u16 (mp->rmt.port)); - -} - -static const quic_echo_cb_vft_t default_cb_vft = { - /* Qsessions */ - .quic_accepted_cb = &echo_on_accept_log_ip, - .quic_connected_cb = &echo_on_connected_connect, - /* client initiated streams */ - .server_stream_accepted_cb = NULL, - .client_stream_connected_cb = &echo_on_connected_send, - /* server initiated streams */ - .client_stream_accepted_cb = &echo_on_accept_error, - .server_stream_connected_cb = &echo_on_connected_error, -}; - -static const quic_echo_cb_vft_t server_stream_cb_vft = { - /* Qsessions */ - .quic_accepted_cb = &echo_on_accept_connect, - .quic_connected_cb = NULL, - /* client initiated streams */ - .server_stream_accepted_cb = &echo_on_accept_error, - .client_stream_connected_cb = &echo_on_connected_error, - /* server initiated streams */ - .client_stream_accepted_cb = &echo_on_accept_recv, - .server_stream_connected_cb = &echo_on_connected_send, -}; - -static uword -echo_unformat_quic_setup_vft (unformat_input_t * input, va_list * args) -{ - echo_main_t *em = &echo_main; - if (unformat (input, "serverstream")) - { - clib_warning ("Using QUIC server initiated streams"); - em->no_return = 1; - em->cb_vft = server_stream_cb_vft; - return 1; - } - else if (unformat (input, "default")) - return 1; - return 0; -} - -static uword -echo_unformat_data (unformat_input_t * input, va_list * args) -{ - u64 _a; - u64 *a = va_arg (*args, u64 *); - if (unformat (input, "%lluGb", &_a)) - { - *a = _a << 30; - return 1; - } - else if (unformat (input, "%lluMb", &_a)) - { - *a = _a << 20; - return 1; - } - else if (unformat (input, "%lluKb", &_a)) - { - *a = _a << 10; - return 1; - } - else if (unformat (input, "%llu", a)) - return 1; - return 0; -} - -/* - * - * End of ECHO callback definitions - * - */ - -static void -session_disconnected_handler (session_disconnected_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - session_disconnected_reply_msg_t *rmp; - echo_main_t *em = &echo_main; - echo_session_t *session = 0; - uword *p; - int rv = 0; - DBG ("Disonnected session handle %lx", mp->handle); - p = hash_get (em->session_index_by_vpp_handles, mp->handle); - if (!p) - { - clib_warning ("couldn't find session key %llx", mp->handle); - return; - } - - session = pool_elt_at_index (em->sessions, p[0]); - hash_unset (em->session_index_by_vpp_handles, mp->handle); - - pool_put (em->sessions, session); - - app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, - SESSION_CTRL_EVT_DISCONNECTED_REPLY); - rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data; - rmp->retval = rv; - rmp->handle = mp->handle; - rmp->context = mp->context; - app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); - - session_print_stats (em, session); -} - -static void -session_reset_handler (session_reset_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - echo_main_t *em = &echo_main; - session_reset_reply_msg_t *rmp; - echo_session_t *session = 0; - uword *p; - int rv = 0; - - DBG ("Reset session handle %lx", mp->handle); - p = hash_get (em->session_index_by_vpp_handles, mp->handle); - - if (p) - { - session = pool_elt_at_index (em->sessions, p[0]); - clib_warning ("got reset"); - /* Cleanup later */ - em->time_to_stop = 1; - } - else - { - clib_warning ("couldn't find session key %llx", mp->handle); - return; - } - - app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, - SESSION_CTRL_EVT_RESET_REPLY); - rmp = (session_reset_reply_msg_t *) app_evt->evt->data; - rmp->retval = rv; - rmp->handle = mp->handle; - app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); -} - -static void -handle_mq_event (echo_main_t * em, session_event_t * e, int handle_rx) -{ - switch (e->event_type) - { - case SESSION_CTRL_EVT_BOUND: - DBG ("SESSION_CTRL_EVT_BOUND"); - session_bound_handler ((session_bound_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_ACCEPTED: - DBG ("SESSION_CTRL_EVT_ACCEPTED"); - session_accepted_handler ((session_accepted_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_CONNECTED: - DBG ("SESSION_CTRL_EVT_CONNECTED"); - session_connected_handler ((session_connected_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_DISCONNECTED: - DBG ("SESSION_CTRL_EVT_DISCONNECTED"); - session_disconnected_handler ((session_disconnected_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_RESET: - DBG ("SESSION_CTRL_EVT_RESET"); - session_reset_handler ((session_reset_msg_t *) e->data); - break; - case SESSION_IO_EVT_RX: - DBG ("SESSION_IO_EVT_RX"); - if (handle_rx) - echo_handle_rx (em, e); - break; - default: - clib_warning ("unhandled event %u", e->event_type); - } -} - -static int -clients_run (echo_main_t * em) -{ - svm_msg_q_msg_t msg; - session_event_t *e; - echo_session_t *s; - hash_pair_t *p; - int i; - - /* - * Attach and connect the clients - */ - if (application_attach (em)) - return -1; - - quic_echo_notify_event (em, ECHO_EVT_FIRST_QCONNECT); - for (i = 0; i < em->n_clients; i++) - echo_send_connect (em, em->uri, QUIC_SESSION_TYPE_QUIC); - - wait_for_state_change (em, STATE_READY, TIMEOUT); - - /* - * Wait for client threads to send the data - */ - DBG ("Waiting for data on %u clients", em->n_clients_connected); - while (em->n_clients_connected) - { - if (svm_msg_q_is_empty (em->our_event_queue)) - continue; - if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_TIMEDWAIT, 1)) - continue; - e = svm_msg_q_msg_data (em->our_event_queue, &msg); - handle_mq_event (em, e, 0 /* handle_rx */ ); - svm_msg_q_free_msg (em->our_event_queue, &msg); - } - - /* *INDENT-OFF* */ - hash_foreach_pair (p, em->session_index_by_vpp_handles, - ({ - s = pool_elt_at_index (em->sessions, p->value[0]); - DBG ("Sending disconnect on session %lu", p->key); - client_disconnect_session (em, s); - })); - /* *INDENT-ON* */ - - wait_for_disconnected_sessions (em); - application_detach (em); - return 0; -} - -static void -vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp) -{ - echo_main_t *em = &echo_main; - if (mp->retval) - { - clib_warning ("bind failed: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - em->state = STATE_FAILED; - return; - } - - em->state = STATE_LISTEN; -} - -static void -vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp) -{ - echo_main_t *em = &echo_main; - - if (mp->retval != 0) - clib_warning ("returned %d", ntohl (mp->retval)); - - em->state = STATE_START; -} - -u8 * -format_ip4_address (u8 * s, va_list * args) -{ - u8 *a = va_arg (*args, u8 *); - return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); -} - -u8 * -format_ip6_address (u8 * s, va_list * args) -{ - ip6_address_t *a = va_arg (*args, ip6_address_t *); - u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon; - - i_max_n_zero = ARRAY_LEN (a->as_u16); - max_n_zeros = 0; - i_first_zero = i_max_n_zero; - n_zeros = 0; - for (i = 0; i < ARRAY_LEN (a->as_u16); i++) - { - u32 is_zero = a->as_u16[i] == 0; - if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16)) - { - i_first_zero = i; - n_zeros = 0; - } - n_zeros += is_zero; - if ((!is_zero && n_zeros > max_n_zeros) - || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros)) - { - i_max_n_zero = i_first_zero; - max_n_zeros = n_zeros; - i_first_zero = ARRAY_LEN (a->as_u16); - n_zeros = 0; - } - } - - last_double_colon = 0; - for (i = 0; i < ARRAY_LEN (a->as_u16); i++) - { - if (i == i_max_n_zero && max_n_zeros > 1) - { - s = format (s, "::"); - i += max_n_zeros - 1; - last_double_colon = 1; - } - else - { - s = format (s, "%s%x", - (last_double_colon || i == 0) ? "" : ":", - clib_net_to_host_u16 (a->as_u16[i])); - last_double_colon = 0; - } - } - - return s; -} - -/* Format an IP46 address. */ -u8 * -format_ip46_address (u8 * s, va_list * args) -{ - ip46_address_t *ip46 = va_arg (*args, ip46_address_t *); - ip46_type_t type = va_arg (*args, ip46_type_t); - int is_ip4 = 1; - - switch (type) - { - case IP46_TYPE_ANY: - is_ip4 = ip46_address_is_ip4 (ip46); - break; - case IP46_TYPE_IP4: - is_ip4 = 1; - break; - case IP46_TYPE_IP6: - is_ip4 = 0; - break; - } - - return is_ip4 ? - format (s, "%U", format_ip4_address, &ip46->ip4) : - format (s, "%U", format_ip6_address, &ip46->ip6); -} - -static void -echo_handle_rx (echo_main_t * em, session_event_t * e) -{ - int n_read, max_dequeue, n_sent; - u32 offset, to_dequeue; - echo_session_t *s; - s = pool_elt_at_index (em->sessions, e->session_index); - - /* Clear event only once. Otherwise, if we do it in the loop by calling - * app_recv_stream, we may end up with a lot of unhandled rx events on the - * message queue */ - svm_fifo_unset_event (s->rx_fifo); - max_dequeue = svm_fifo_max_dequeue (s->rx_fifo); - if (PREDICT_FALSE (!max_dequeue)) - return; - do - { - /* The options here are to limit ourselves to max_dequeue or read - * even the data that was enqueued while we were dequeueing and which - * now has an rx event in the mq. Either of the two work. */ - to_dequeue = clib_min (max_dequeue, vec_len (em->rx_buf)); - n_read = app_recv_stream_raw (s->rx_fifo, em->rx_buf, to_dequeue, - 0 /* clear evt */ , 0 /* peek */ ); - - if (n_read <= 0) - break; - DBG ("Notify cause %u bytes", n_read); - notify_rx_data_to_vpp (s); - if (em->test_return_packets) - test_recv_bytes (em, s, em->rx_buf, n_read); - - max_dequeue -= n_read; - s->bytes_received += n_read; - s->bytes_to_receive -= n_read; - - /* Reflect if a non-drop session */ - if (!em->no_return) - { - offset = 0; - do - { - n_sent = app_send_stream ((app_session_t *) s, - em->rx_buf + offset, - n_read, SVM_Q_WAIT); - if (n_sent <= 0) - continue; - n_read -= n_sent; - s->bytes_to_send -= n_sent; - s->bytes_sent += n_sent; - offset += n_sent; - } - while (n_read > 0); - } - } - while (max_dequeue > 0 && !em->time_to_stop); -} - -static void -server_handle_mq (echo_main_t * em) -{ - svm_msg_q_msg_t msg; - session_event_t *e; - - while (1) - { - int rc = svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_TIMEDWAIT, 1); - if (PREDICT_FALSE (rc == ETIMEDOUT && em->time_to_stop)) - break; - if (rc == ETIMEDOUT) - continue; - e = svm_msg_q_msg_data (em->our_event_queue, &msg); - handle_mq_event (em, e, em->state == STATE_READY /* handle_rx */ ); - svm_msg_q_free_msg (em->our_event_queue, &msg); - } -} - -static void -server_send_listen (echo_main_t * em) -{ - vl_api_bind_uri_t *bmp; - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_BIND_URI); - bmp->client_index = em->my_client_index; - bmp->context = ntohl (0xfeedface); - memcpy (bmp->uri, em->uri, vec_len (em->uri)); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); -} - -static void -server_send_unbind (echo_main_t * em) -{ - vl_api_unbind_uri_t *ump; - - ump = vl_msg_api_alloc (sizeof (*ump)); - clib_memset (ump, 0, sizeof (*ump)); - - ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI); - ump->client_index = em->my_client_index; - memcpy (ump->uri, em->uri, vec_len (em->uri)); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & ump); -} - -static int -server_run (echo_main_t * em) -{ - echo_session_t *session; - int i; - - /* $$$$ hack preallocation */ - for (i = 0; i < 200000; i++) - { - pool_get (em->sessions, session); - clib_memset (session, 0, sizeof (*session)); - } - for (i = 0; i < 200000; i++) - pool_put_index (em->sessions, i); - - if (application_attach (em)) - return -1; - - /* Bind to uri */ - server_send_listen (em); - if (wait_for_state_change (em, STATE_READY, 0)) - return -2; - - /* Enter handle event loop */ - server_handle_mq (em); - - /* Cleanup */ - server_send_unbind (em); - application_detach (em); - fformat (stdout, "Test complete...\n"); - return 0; -} - -static void -vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t * - mp) -{ - echo_main_t *em = &echo_main; - uword *p; - DBG ("Got disonnected reply for session handle %lu", mp->handle); - em->state = STATE_START; - - p = hash_get (em->session_index_by_vpp_handles, mp->handle); - if (p) - hash_unset (em->session_index_by_vpp_handles, mp->handle); - else - clib_warning ("couldn't find session key %llx", mp->handle); - - if (mp->retval) - clib_warning ("vpp complained about disconnect: %d", ntohl (mp->retval)); -} - -static void - vl_api_application_tls_cert_add_reply_t_handler - (vl_api_application_tls_cert_add_reply_t * mp) -{ - if (mp->retval) - clib_warning ("failed to add tls cert"); -} - -static void - vl_api_application_tls_key_add_reply_t_handler - (vl_api_application_tls_key_add_reply_t * mp) -{ - if (mp->retval) - clib_warning ("failed to add tls key"); -} - -#define foreach_quic_echo_msg \ -_(BIND_URI_REPLY, bind_uri_reply) \ -_(UNBIND_URI_REPLY, unbind_uri_reply) \ -_(DISCONNECT_SESSION_REPLY, disconnect_session_reply) \ -_(APPLICATION_ATTACH_REPLY, application_attach_reply) \ -_(APPLICATION_DETACH_REPLY, application_detach_reply) \ -_(MAP_ANOTHER_SEGMENT, map_another_segment) \ -_(APPLICATION_TLS_CERT_ADD_REPLY, application_tls_cert_add_reply) \ -_(APPLICATION_TLS_KEY_ADD_REPLY, application_tls_key_add_reply) \ - -void -quic_echo_api_hookup (echo_main_t * em) -{ -#define _(N,n) \ - vl_msg_api_set_handlers(VL_API_##N, #n, \ - vl_api_##n##_t_handler, \ - vl_noop_handler, \ - vl_api_##n##_t_endian, \ - vl_api_##n##_t_print, \ - sizeof(vl_api_##n##_t), 1); - foreach_quic_echo_msg; -#undef _ -} - -static void -print_usage_and_exit (void) -{ - fprintf (stderr, - "quic_echo [socket-name SOCKET] [client|server] [uri URI] [OPTIONS]\n" - "\n" - " socket-name PATH Specify the binary socket path to connect to VPP\n" - " use-svm-api Use SVM API to connect to VPP\n" - " test-bytes[:assert] Check data correctness when receiving (assert fails on first error)\n" - " fifo-size N Use N Kb fifos\n" - " appns NAMESPACE Use the namespace NAMESPACE\n" - " all-scope all-scope option\n" - " local-scope local-scope option\n" - " global-scope global-scope option\n" - " secret SECRET set namespace secret\n" - " chroot prefix PATH Use PATH as memory root path\n" - " quic-setup OPT OPT=serverstream : Client open N connections. On each one server opens M streams\n" - " by default : Client open N connections. On each one client opens M streams\n" - "\n" - " no-return Drop the data when received, dont reply\n" - " nclients N[/M] Open N QUIC connections, each one with M streams (M defaults to 1)\n" - " send N[Kb|Mb|GB] Send N [K|M|G]bytes\n" - " recv N[Kb|Mb|GB] Expect N [K|M|G]bytes\n" - " nclients N[/M] Open N QUIC connections, each one with M streams (M defaults to 1)\n"); - exit (1); -} - - -void -quic_echo_process_opts (int argc, char **argv) -{ - echo_main_t *em = &echo_main; - unformat_input_t _argv, *a = &_argv; - u32 tmp; - u8 *chroot_prefix; - u8 *uri = 0; - - unformat_init_command_line (a, argv); - while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT) - { - if (unformat (a, "chroot prefix %s", &chroot_prefix)) - { - vl_set_memory_root_path ((char *) chroot_prefix); - } - else if (unformat (a, "uri %s", &uri)) - em->uri = format (0, "%s%c", uri, 0); - else if (unformat (a, "server")) - em->i_am_master = 1; - else if (unformat (a, "client")) - em->i_am_master = 0; - else if (unformat (a, "no-return")) - em->no_return = 1; - else if (unformat (a, "test-bytes:assert")) - em->test_return_packets = RETURN_PACKETS_ASSERT; - else if (unformat (a, "test-bytes")) - em->test_return_packets = RETURN_PACKETS_LOG_WRONG; - else if (unformat (a, "socket-name %s", &em->socket_name)) - ; - else if (unformat (a, "use-svm-api")) - em->use_sock_api = 0; - else if (unformat (a, "fifo-size %d", &tmp)) - em->fifo_size = tmp << 10; - else - if (unformat - (a, "nclients %d/%d", &em->n_clients, &em->n_stream_clients)) - ; - else if (unformat (a, "nclients %d", &em->n_clients)) - ; - else if (unformat (a, "appns %_%v%_", &em->appns_id)) - ; - else if (unformat (a, "all-scope")) - em->appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE - | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE); - else if (unformat (a, "local-scope")) - em->appns_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE; - else if (unformat (a, "global-scope")) - em->appns_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE; - else if (unformat (a, "secret %lu", &em->appns_secret)) - ; - else if (unformat (a, "quic-setup %U", echo_unformat_quic_setup_vft)) - ; - else - if (unformat (a, "send %U", echo_unformat_data, &em->bytes_to_send)) - ; - else - if (unformat - (a, "recv %U", echo_unformat_data, &em->bytes_to_receive)) - ; - else if (unformat (a, "time %U:%U", - echo_unformat_timing_event, &em->timing_start_event, - echo_unformat_timing_event, &em->timing_end_event)) - ; - else - print_usage_and_exit (); - } -} - -int -main (int argc, char **argv) -{ - echo_main_t *em = &echo_main; - fifo_segment_main_t *sm = &em->segment_main; - char *app_name; - int i, rv; - u32 n_clients; - - clib_mem_init_thread_safe (0, 256 << 20); - clib_memset (em, 0, sizeof (*em)); - em->session_index_by_vpp_handles = hash_create (0, sizeof (uword)); - em->shared_segment_handles = hash_create (0, sizeof (uword)); - em->my_pid = getpid (); - em->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0); - em->use_sock_api = 1; - em->fifo_size = 64 << 10; - em->n_clients = 1; - em->n_stream_clients = 1; - em->max_test_msg = 50; - em->time_to_stop = 0; - em->i_am_master = 1; - em->test_return_packets = RETURN_PACKETS_NOTEST; - em->timing_start_event = ECHO_EVT_FIRST_QCONNECT; - em->timing_end_event = ECHO_EVT_LAST_BYTE; - em->bytes_to_receive = 64 << 10; - em->bytes_to_send = 64 << 10; - em->uri = format (0, "%s%c", "quic://0.0.0.0/1234", 0); - em->cb_vft = default_cb_vft; - quic_echo_process_opts (argc, argv); - - n_clients = em->n_clients * em->n_stream_clients; - vec_validate (em->client_thread_handles, n_clients - 1); - vec_validate (em->thread_args, n_clients - 1); - clib_time_init (&em->clib_time); - init_error_string_table (em); - fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20); - clib_spinlock_init (&em->segment_handles_lock); - vec_validate (em->rx_buf, 4 << 20); - vec_validate (em->connect_test_data, 1024 * 1024 - 1); - for (i = 0; i < vec_len (em->connect_test_data); i++) - em->connect_test_data[i] = i & 0xff; - - setup_signal_handlers (); - quic_echo_api_hookup (em); - - app_name = em->i_am_master ? "quic_echo_server" : "quic_echo_client"; - if (connect_to_vpp (app_name) < 0) - { - svm_region_exit (); - fformat (stderr, "Couldn't connect to vpe, exiting...\n"); - exit (1); - } - - quic_echo_notify_event (em, ECHO_EVT_START); - if (em->i_am_master) - rv = server_run (em); - else - rv = clients_run (em); - if (rv) - exit (rv); - quic_echo_notify_event (em, ECHO_EVT_EXIT); - print_global_stats (em); - - /* Make sure detach finishes */ - if (wait_for_state_change (em, STATE_DETACHED, TIMEOUT)) - exit (-1); - disconnect_from_vpp (em); - exit (0); -} - -/* - * fd.io coding-style-patch-verification: ON - * - * Local Variables: - * eval: (c-set-style "gnu") - * End: - */ diff --git a/src/plugins/hs_apps/sapi/quic_echo.c b/src/plugins/hs_apps/sapi/quic_echo.c new file mode 100644 index 00000000000..a62af642b2f --- /dev/null +++ b/src/plugins/hs_apps/sapi/quic_echo.c @@ -0,0 +1,1841 @@ +/* + * Copyright (c) 2019 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include +#include + +#define vl_typedefs /* define message structures */ +#include +#undef vl_typedefs + +/* declare message handlers for each api */ + +#define vl_endianfun /* define message structures */ +#include +#undef vl_endianfun + +/* instantiate all the print functions we know about */ +#define vl_print(handle, ...) +#define vl_printfun +#include +#undef vl_printfun + +#define QUIC_ECHO_DBG 0 +#define DBG(_fmt, _args...) \ + if (QUIC_ECHO_DBG) \ + clib_warning (_fmt, ##_args) + +typedef struct +{ + CLIB_CACHE_LINE_ALIGN_MARK (cacheline0); +#define _(type, name) type name; + foreach_app_session_field +#undef _ + u64 vpp_session_handle; + u64 bytes_sent; + u64 bytes_to_send; + volatile u64 bytes_received; + volatile u64 bytes_to_receive; + f64 start; +} echo_session_t; + +typedef enum +{ + STATE_START, + STATE_ATTACHED, + STATE_LISTEN, + STATE_READY, + STATE_DISCONNECTING, + STATE_FAILED, + STATE_DETACHED +} connection_state_t; + +typedef enum +{ + ECHO_EVT_START, /* app starts */ + ECHO_EVT_FIRST_QCONNECT, /* First connect Quic session sent */ + ECHO_EVT_LAST_QCONNECTED, /* All Quic session are connected */ + ECHO_EVT_FIRST_SCONNECT, /* First connect Stream session sent */ + ECHO_EVT_LAST_SCONNECTED, /* All Stream session are connected */ + ECHO_EVT_LAST_BYTE, /* Last byte received */ + ECHO_EVT_EXIT, /* app exits */ +} echo_test_evt_t; + +enum quic_session_type_t +{ + QUIC_SESSION_TYPE_QUIC = 0, + QUIC_SESSION_TYPE_STREAM = 1, + QUIC_SESSION_TYPE_LISTEN = INT32_MAX, +}; + +typedef struct _quic_echo_cb_vft +{ + void (*quic_connected_cb) (session_connected_msg_t * mp, u32 session_index); + void (*client_stream_connected_cb) (session_connected_msg_t * mp, + u32 session_index); + void (*server_stream_connected_cb) (session_connected_msg_t * mp, + u32 session_index); + void (*quic_accepted_cb) (session_accepted_msg_t * mp, u32 session_index); + void (*client_stream_accepted_cb) (session_accepted_msg_t * mp, + u32 session_index); + void (*server_stream_accepted_cb) (session_accepted_msg_t * mp, + u32 session_index); +} quic_echo_cb_vft_t; + + +typedef enum +{ + RETURN_PACKETS_NOTEST, + RETURN_PACKETS_LOG_WRONG, + RETURN_PACKETS_ASSERT, +} test_return_packets_t; + +typedef struct +{ + /* vpe input queue */ + svm_queue_t *vl_input_queue; + + /* API client handle */ + u32 my_client_index; + + /* The URI we're playing with */ + u8 *uri; + + /* Session pool */ + echo_session_t *sessions; + + /* Hash table for disconnect processing */ + uword *session_index_by_vpp_handles; + /* Handle of vpp listener session */ + u64 listener_handle; + + /* Hash table for shared segment_names */ + uword *shared_segment_handles; + clib_spinlock_t segment_handles_lock; + + /* intermediate rx buffer */ + u8 *rx_buf; + + int i_am_master; + + /* drop all packets */ + int no_return; + + /* Our event queue */ + svm_msg_q_t *our_event_queue; + + u8 *socket_name; + + pid_t my_pid; + + /* For deadman timers */ + clib_time_t clib_time; + + /* State of the connection, shared between msg RX thread and main thread */ + volatile connection_state_t state; + + /* Signal variables */ + volatile int time_to_stop; + + /* VNET_API_ERROR_FOO -> "Foo" hash table */ + uword *error_string_by_error_number; + + u8 *connect_test_data; + pthread_t *client_thread_handles; + u32 *thread_args; + u8 test_return_packets; + u64 bytes_to_send; + u64 bytes_to_receive; + u32 fifo_size; + + u8 *appns_id; + u64 appns_flags; + u64 appns_secret; + + u32 n_clients; /* Target number of QUIC sessions */ + u32 n_stream_clients; /* Target Number of STREAM sessions per QUIC session */ + volatile u32 n_quic_clients_connected; /* Number of connected QUIC sessions */ + volatile u32 n_clients_connected; /* Number of STREAM sessions connected */ + + u64 tx_total; + u64 rx_total; + + /* Event based timing : start & end depend on CLI specified events */ + u8 first_sconnect_sent; /* Sent the first Stream session connect ? */ + f64 start_time; + f64 end_time; + u8 timing_start_event; + u8 timing_end_event; + + /* cb vft for QUIC scenarios */ + quic_echo_cb_vft_t cb_vft; + + /** Flag that decides if socket, instead of svm, api is used to connect to + * vpp. If sock api is used, shm binary api is subsequently bootstrapped + * and all other messages are exchanged using shm IPC. */ + u8 use_sock_api; + + /* Limit the number of incorrect data messages */ + int max_test_msg; + + fifo_segment_main_t segment_main; +} echo_main_t; + +echo_main_t echo_main; + +#if CLIB_DEBUG > 0 +#define NITER 10000 +#else +#define NITER 4000000 +#endif + +#if CLIB_DEBUG > 0 +#define TIMEOUT 10.0 +#else +#define TIMEOUT 10.0 +#endif + +u8 * +format_quic_echo_state (u8 * s, va_list * args) +{ + u32 state = va_arg (*args, u32); + if (state == STATE_START) + return format (s, "STATE_START"); + if (state == STATE_ATTACHED) + return format (s, "STATE_ATTACHED"); + if (state == STATE_LISTEN) + return format (s, "STATE_LISTEN"); + if (state == STATE_READY) + return format (s, "STATE_READY"); + if (state == STATE_DISCONNECTING) + return format (s, "STATE_DISCONNECTING"); + if (state == STATE_FAILED) + return format (s, "STATE_FAILED"); + if (state == STATE_DETACHED) + return format (s, "STATE_DETACHED"); + else + return format (s, "unknown state"); +} + +static u8 * +format_api_error (u8 * s, va_list * args) +{ + echo_main_t *em = &echo_main; + i32 error = va_arg (*args, u32); + uword *p; + + p = hash_get (em->error_string_by_error_number, -error); + + if (p) + s = format (s, "%s", p[0]); + else + s = format (s, "%d", error); + return s; +} + +static void +quic_echo_notify_event (echo_main_t * em, echo_test_evt_t e) +{ + if (em->timing_start_event == e) + em->start_time = clib_time_now (&em->clib_time); + else if (em->timing_end_event == e) + em->end_time = clib_time_now (&em->clib_time); +} + +static uword +echo_unformat_timing_event (unformat_input_t * input, va_list * args) +{ + echo_test_evt_t *a = va_arg (*args, echo_test_evt_t *); + if (unformat (input, "start")) + *a = ECHO_EVT_START; + else if (unformat (input, "qconnect")) + *a = ECHO_EVT_FIRST_QCONNECT; + else if (unformat (input, "qconnected")) + *a = ECHO_EVT_LAST_QCONNECTED; + else if (unformat (input, "sconnect")) + *a = ECHO_EVT_FIRST_SCONNECT; + else if (unformat (input, "sconnected")) + *a = ECHO_EVT_LAST_SCONNECTED; + else if (unformat (input, "lastbyte")) + *a = ECHO_EVT_LAST_BYTE; + else if (unformat (input, "exit")) + *a = ECHO_EVT_EXIT; + else + return 0; + return 1; +} + +u8 * +echo_format_timing_event (u8 * s, va_list * args) +{ + u32 timing_event = va_arg (*args, u32); + if (timing_event == ECHO_EVT_START) + return format (s, "start"); + if (timing_event == ECHO_EVT_FIRST_QCONNECT) + return format (s, "qconnect"); + if (timing_event == ECHO_EVT_LAST_QCONNECTED) + return format (s, "qconnected"); + if (timing_event == ECHO_EVT_FIRST_SCONNECT) + return format (s, "sconnect"); + if (timing_event == ECHO_EVT_LAST_SCONNECTED) + return format (s, "sconnected"); + if (timing_event == ECHO_EVT_LAST_BYTE) + return format (s, "lastbyte"); + if (timing_event == ECHO_EVT_EXIT) + return format (s, "exit"); + else + return format (s, "unknown timing event"); +} + +static void +init_error_string_table (echo_main_t * em) +{ + em->error_string_by_error_number = hash_create (0, sizeof (uword)); + +#define _(n,v,s) hash_set (em->error_string_by_error_number, -v, s); + foreach_vnet_api_error; +#undef _ + + hash_set (em->error_string_by_error_number, 99, "Misc"); +} + +static void handle_mq_event (echo_main_t * em, session_event_t * e, + int handle_rx); +static void echo_handle_rx (echo_main_t * em, session_event_t * e); + +static int +wait_for_segment_allocation (u64 segment_handle) +{ + echo_main_t *em = &echo_main; + f64 timeout; + timeout = clib_time_now (&em->clib_time) + TIMEOUT; + uword *segment_present; + DBG ("Waiting for segment %lx...", segment_handle); + while (clib_time_now (&em->clib_time) < timeout) + { + clib_spinlock_lock (&em->segment_handles_lock); + segment_present = hash_get (em->shared_segment_handles, segment_handle); + clib_spinlock_unlock (&em->segment_handles_lock); + if (segment_present != 0) + return 0; + if (em->time_to_stop == 1) + return 0; + } + DBG ("timeout waiting for segment_allocation %lx", segment_handle); + return -1; +} + +static int +wait_for_disconnected_sessions (echo_main_t * em) +{ + f64 timeout; + timeout = clib_time_now (&em->clib_time) + TIMEOUT; + while (clib_time_now (&em->clib_time) < timeout) + { + if (hash_elts (em->session_index_by_vpp_handles) == 0) + return 0; + } + DBG ("timeout waiting for disconnected_sessions"); + return -1; +} + +static int +wait_for_state_change (echo_main_t * em, connection_state_t state, + f64 timeout) +{ + svm_msg_q_msg_t msg; + session_event_t *e; + f64 end_time = clib_time_now (&em->clib_time) + timeout; + + while (!timeout || clib_time_now (&em->clib_time) < end_time) + { + if (em->state == state) + return 0; + if (em->state == STATE_FAILED) + return -1; + if (em->time_to_stop == 1) + return 0; + if (!em->our_event_queue || em->state < STATE_ATTACHED) + continue; + + if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_NOWAIT, 0)) + continue; + e = svm_msg_q_msg_data (em->our_event_queue, &msg); + handle_mq_event (em, e, 0 /* handle_rx */ ); + svm_msg_q_free_msg (em->our_event_queue, &msg); + } + clib_warning ("timeout waiting for state %U", format_quic_echo_state, + state); + return -1; +} + +static void +notify_rx_data_to_vpp (echo_session_t * s) +{ + svm_fifo_t *f = s->tx_fifo; + return; /* FOR NOW */ + if (svm_fifo_set_event (f)) + { + DBG ("did send event"); + app_send_io_evt_to_vpp (s->vpp_evt_q, f->master_session_index, + SESSION_IO_EVT_TX, 0 /* noblock */ ); + } +} + +void +application_send_attach (echo_main_t * em) +{ + vl_api_application_attach_t *bmp; + vl_api_application_tls_cert_add_t *cert_mp; + vl_api_application_tls_key_add_t *key_mp; + + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH); + bmp->client_index = em->my_client_index; + bmp->context = ntohl (0xfeedface); + bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ACCEPT_REDIRECT; + bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_ADD_SEGMENT; + bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 16; + bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = em->fifo_size; + bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = em->fifo_size; + bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20; + bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20; + bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 256; + if (em->appns_id) + { + bmp->namespace_id_len = vec_len (em->appns_id); + clib_memcpy_fast (bmp->namespace_id, em->appns_id, + bmp->namespace_id_len); + bmp->options[APP_OPTIONS_FLAGS] |= em->appns_flags; + bmp->options[APP_OPTIONS_NAMESPACE_SECRET] = em->appns_secret; + } + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); + + cert_mp = vl_msg_api_alloc (sizeof (*cert_mp) + test_srv_crt_rsa_len); + clib_memset (cert_mp, 0, sizeof (*cert_mp)); + cert_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_CERT_ADD); + cert_mp->client_index = em->my_client_index; + cert_mp->context = ntohl (0xfeedface); + cert_mp->cert_len = clib_host_to_net_u16 (test_srv_crt_rsa_len); + clib_memcpy_fast (cert_mp->cert, test_srv_crt_rsa, test_srv_crt_rsa_len); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cert_mp); + + key_mp = vl_msg_api_alloc (sizeof (*key_mp) + test_srv_key_rsa_len); + clib_memset (key_mp, 0, sizeof (*key_mp) + test_srv_key_rsa_len); + key_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_KEY_ADD); + key_mp->client_index = em->my_client_index; + key_mp->context = ntohl (0xfeedface); + key_mp->key_len = clib_host_to_net_u16 (test_srv_key_rsa_len); + clib_memcpy_fast (key_mp->key, test_srv_key_rsa, test_srv_key_rsa_len); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & key_mp); +} + +static int +application_attach (echo_main_t * em) +{ + application_send_attach (em); + return wait_for_state_change (em, STATE_ATTACHED, TIMEOUT); +} + +void +application_detach (echo_main_t * em) +{ + vl_api_application_detach_t *bmp; + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH); + bmp->client_index = em->my_client_index; + bmp->context = ntohl (0xfeedface); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); + + DBG ("%s", "Sent detach"); +} + +static int +ssvm_segment_attach (char *name, ssvm_segment_type_t type, int fd) +{ + fifo_segment_create_args_t _a, *a = &_a; + fifo_segment_main_t *sm = &echo_main.segment_main; + int rv; + + clib_memset (a, 0, sizeof (*a)); + a->segment_name = (char *) name; + a->segment_type = type; + + if (type == SSVM_SEGMENT_MEMFD) + a->memfd_fd = fd; + + if ((rv = fifo_segment_attach (sm, a))) + { + clib_warning ("svm_fifo_segment_attach ('%s') failed", name); + return rv; + } + vec_reset_length (a->new_segment_indices); + return 0; +} + +static void +vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t * + mp) +{ + echo_main_t *em = &echo_main; + int *fds = 0; + u32 n_fds = 0; + u64 segment_handle; + segment_handle = clib_net_to_host_u64 (mp->segment_handle); + DBG ("Attached returned app %u", htons (mp->app_index)); + + if (mp->retval) + { + clib_warning ("attach failed: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + goto failed; + } + + if (mp->segment_name_length == 0) + { + clib_warning ("segment_name_length zero"); + goto failed; + } + + ASSERT (mp->app_event_queue_address); + em->our_event_queue = uword_to_pointer (mp->app_event_queue_address, + svm_msg_q_t *); + + if (mp->n_fds) + { + vec_validate (fds, mp->n_fds); + vl_socket_client_recv_fd_msg (fds, mp->n_fds, 5); + + if (mp->fd_flags & SESSION_FD_F_VPP_MQ_SEGMENT) + if (ssvm_segment_attach (0, SSVM_SEGMENT_MEMFD, fds[n_fds++])) + goto failed; + + if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT) + if (ssvm_segment_attach ((char *) mp->segment_name, + SSVM_SEGMENT_MEMFD, fds[n_fds++])) + goto failed; + + if (mp->fd_flags & SESSION_FD_F_MQ_EVENTFD) + svm_msg_q_set_consumer_eventfd (em->our_event_queue, fds[n_fds++]); + + vec_free (fds); + } + else + { + if (ssvm_segment_attach ((char *) mp->segment_name, SSVM_SEGMENT_SHM, + -1)) + goto failed; + } + clib_spinlock_lock (&em->segment_handles_lock); + hash_set (em->shared_segment_handles, segment_handle, 1); + clib_spinlock_unlock (&em->segment_handles_lock); + DBG ("Mapped new segment %lx", segment_handle); + + em->state = STATE_ATTACHED; + return; +failed: + em->state = STATE_FAILED; + return; +} + +static void +vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t * + mp) +{ + if (mp->retval) + clib_warning ("detach returned with err: %d", mp->retval); + echo_main.state = STATE_DETACHED; +} + +static void +stop_signal (int signum) +{ + echo_main_t *um = &echo_main; + um->time_to_stop = 1; +} + +static clib_error_t * +setup_signal_handlers (void) +{ + signal (SIGINT, stop_signal); + signal (SIGQUIT, stop_signal); + signal (SIGTERM, stop_signal); + return 0; +} + +int +connect_to_vpp (char *name) +{ + echo_main_t *em = &echo_main; + api_main_t *am = &api_main; + + if (em->use_sock_api) + { + if (vl_socket_client_connect ((char *) em->socket_name, name, + 0 /* default rx, tx buffer */ )) + { + clib_warning ("socket connect failed"); + return -1; + } + + if (vl_socket_client_init_shm (0, 1 /* want_pthread */ )) + { + clib_warning ("init shm api failed"); + return -1; + } + } + else + { + if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0) + { + clib_warning ("shmem connect failed"); + return -1; + } + } + em->vl_input_queue = am->shmem_hdr->vl_input_queue; + em->my_client_index = am->my_client_index; + return 0; +} + +void +disconnect_from_vpp (echo_main_t * em) +{ + if (em->use_sock_api) + vl_socket_client_disconnect (); + else + vl_client_disconnect_from_vlib (); +} + +static void +vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp) +{ + fifo_segment_main_t *sm = &echo_main.segment_main; + fifo_segment_create_args_t _a, *a = &_a; + echo_main_t *em = &echo_main; + int rv; + int *fds = 0; + u64 segment_handle; + segment_handle = clib_net_to_host_u64 (mp->segment_handle); + + if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT) + { + vec_validate (fds, 1); + vl_socket_client_recv_fd_msg (fds, 1, 5); + if (ssvm_segment_attach + ((char *) mp->segment_name, SSVM_SEGMENT_MEMFD, fds[0])) + clib_warning + ("svm_fifo_segment_attach ('%s') failed on SSVM_SEGMENT_MEMFD", + mp->segment_name); + clib_spinlock_lock (&em->segment_handles_lock); + hash_set (em->shared_segment_handles, segment_handle, 1); + clib_spinlock_unlock (&em->segment_handles_lock); + vec_free (fds); + DBG ("Mapped new segment %lx", segment_handle); + return; + } + + clib_memset (a, 0, sizeof (*a)); + a->segment_name = (char *) mp->segment_name; + a->segment_size = mp->segment_size; + /* Attach to the segment vpp created */ + rv = fifo_segment_attach (sm, a); + if (rv) + { + clib_warning ("svm_fifo_segment_attach ('%s') failed", + mp->segment_name); + return; + } + clib_spinlock_lock (&em->segment_handles_lock); + hash_set (em->shared_segment_handles, mp->segment_name, 1); + clib_spinlock_unlock (&em->segment_handles_lock); + clib_warning ("Mapped new segment '%s' size %d", mp->segment_name, + mp->segment_size); +} + +static void +session_print_stats (echo_main_t * em, echo_session_t * session) +{ + f64 deltat = clib_time_now (&em->clib_time) - session->start; + fformat (stdout, "Session %x done in %.6fs RX[%.4f] TX[%.4f] Gbit/s\n", + session->session_index, deltat, + (session->bytes_received * 8.0) / deltat / 1e9, + (session->bytes_sent * 8.0) / deltat / 1e9); +} + +static void +print_global_stats (echo_main_t * em) +{ + f64 deltat = em->end_time - em->start_time; + u8 *s = format (0, "%U:%U", + echo_format_timing_event, em->timing_start_event, + echo_format_timing_event, em->timing_end_event); + fformat (stdout, "Timinig %s\n", s); + fformat (stdout, "-------- TX --------\n"); + fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds\n", + em->tx_total, em->tx_total / (1ULL << 20), + em->tx_total / (1ULL << 30), deltat); + fformat (stdout, "%.4f Gbit/second\n", (em->tx_total * 8.0) / deltat / 1e9); + fformat (stdout, "-------- RX --------\n"); + fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds\n", + em->rx_total, em->rx_total / (1ULL << 20), + em->rx_total / (1ULL << 30), deltat); + fformat (stdout, "%.4f Gbit/second\n", (em->rx_total * 8.0) / deltat / 1e9); + fformat (stdout, "--------------------\n"); +} + + +static void +test_recv_bytes (echo_main_t * em, echo_session_t * s, u8 * rx_buf, + u32 n_read) +{ + int i; + u8 expected; + for (i = 0; i < n_read; i++) + { + expected = (s->bytes_received + i) & 0xff; + if (rx_buf[i] != expected && em->max_test_msg > 0) + { + clib_warning + ("Session[%lx][0x%lx] byte[%lld], got 0x%x but expected 0x%x", + s->session_index, s->vpp_session_handle, s->bytes_received + i, + rx_buf[i], expected); + em->max_test_msg--; + if (em->max_test_msg == 0) + clib_warning ("Too many errors, hiding next ones"); + if (em->test_return_packets == RETURN_PACKETS_ASSERT) + ASSERT (0); + } + } +} + +static void +recv_data_chunk (echo_main_t * em, echo_session_t * s, u8 * rx_buf) +{ + int n_to_read, n_read; + + n_to_read = svm_fifo_max_dequeue (s->rx_fifo); + if (!n_to_read) + return; + + do + { + n_read = + app_recv_stream ((app_session_t *) s, rx_buf, vec_len (rx_buf)); + if (n_read <= 0) + break; + notify_rx_data_to_vpp (s); + if (em->test_return_packets) + test_recv_bytes (em, s, rx_buf, n_read); + + ASSERT (s->bytes_to_receive >= n_read); + n_to_read -= n_read; + s->bytes_received += n_read; + s->bytes_to_receive -= n_read; + } + while (n_to_read > 0); +} + +static void +send_data_chunk (echo_main_t * em, echo_session_t * s) +{ + u64 test_buf_len, bytes_this_chunk, test_buf_offset; + u8 *test_data = em->connect_test_data; + int n_sent; + + test_buf_len = vec_len (test_data); + test_buf_offset = s->bytes_sent % test_buf_len; + bytes_this_chunk = clib_min (test_buf_len - test_buf_offset, + s->bytes_to_send); + + n_sent = app_send_stream ((app_session_t *) s, test_data + test_buf_offset, + bytes_this_chunk, 0); + + if (n_sent > 0) + { + s->bytes_to_send -= n_sent; + s->bytes_sent += n_sent; + } +} + +/* + * Rx/Tx polling thread per connection + */ +static void * +client_thread_fn (void *arg) +{ + echo_main_t *em = &echo_main; + u8 *rx_buf = 0; + u32 session_index = *(u32 *) arg; + echo_session_t *s; + + vec_validate (rx_buf, 1 << 20); + + while (!em->time_to_stop && em->state != STATE_READY) + ; + + s = pool_elt_at_index (em->sessions, session_index); + while (!em->time_to_stop) + { + send_data_chunk (em, s); + recv_data_chunk (em, s, rx_buf); + if (!s->bytes_to_send && !s->bytes_to_receive) + break; + } + + DBG ("[%lu/%lu] -> S(%x) -> [%lu/%lu]", + s->bytes_received, s->bytes_received + s->bytes_to_receive, + session_index, s->bytes_sent, s->bytes_sent + s->bytes_to_send); + em->tx_total += s->bytes_sent; + em->rx_total += s->bytes_received; + em->n_clients_connected--; + + if (em->n_clients_connected == 0) + quic_echo_notify_event (em, ECHO_EVT_LAST_BYTE); + + pthread_exit (0); +} + +static void +echo_send_connect (echo_main_t * em, u8 * uri, u32 opaque) +{ + vl_api_connect_uri_t *cmp; + cmp = vl_msg_api_alloc (sizeof (*cmp)); + clib_memset (cmp, 0, sizeof (*cmp)); + + cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI); + cmp->client_index = em->my_client_index; + cmp->context = ntohl (opaque); + memcpy (cmp->uri, uri, vec_len (uri)); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cmp); +} + +static void +client_disconnect_session (echo_main_t * em, echo_session_t * s) +{ + vl_api_disconnect_session_t *dmp; + dmp = vl_msg_api_alloc (sizeof (*dmp)); + clib_memset (dmp, 0, sizeof (*dmp)); + dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION); + dmp->client_index = em->my_client_index; + dmp->handle = s->vpp_session_handle; + DBG ("Sending Session disonnect handle %lu", dmp->handle); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & dmp); + pool_put (em->sessions, s); + clib_memset (s, 0xfe, sizeof (*s)); +} + +static void +session_bound_handler (session_bound_msg_t * mp) +{ + echo_main_t *em = &echo_main; + + if (mp->retval) + { + clib_warning ("bind failed: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + em->state = STATE_FAILED; + return; + } + + clib_warning ("listening on %U:%u", format_ip46_address, mp->lcl_ip, + mp->lcl_is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6, + clib_net_to_host_u16 (mp->lcl_port)); + em->listener_handle = mp->handle; + em->state = STATE_LISTEN; +} + +static void +session_accepted_handler (session_accepted_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + session_accepted_reply_msg_t *rmp; + svm_fifo_t *rx_fifo, *tx_fifo; + echo_main_t *em = &echo_main; + echo_session_t *session; + u32 session_index; + + /* Allocate local session and set it up */ + pool_get (em->sessions, session); + session_index = session - em->sessions; + + if (wait_for_segment_allocation (mp->segment_handle)) + return; + + rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); + rx_fifo->client_session_index = session_index; + tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); + tx_fifo->client_session_index = session_index; + + session->rx_fifo = rx_fifo; + session->tx_fifo = tx_fifo; + session->session_index = session_index; + session->vpp_session_handle = mp->handle; + session->start = clib_time_now (&em->clib_time); + session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, + svm_msg_q_t *); + + /* Add it to lookup table */ + DBG ("Accepted session handle %lx, Listener %lx idx %lu", mp->handle, + mp->listener_handle, session_index); + hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); + + app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, + SESSION_CTRL_EVT_ACCEPTED_REPLY); + rmp = (session_accepted_reply_msg_t *) app_evt->evt->data; + rmp->handle = mp->handle; + rmp->context = mp->context; + app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); + + DBG ("SSession handle is %lu", mp->handle); + if (mp->listener_handle == em->listener_handle) + { + if (em->cb_vft.quic_accepted_cb) + em->cb_vft.quic_accepted_cb (mp, session_index); + em->n_quic_clients_connected++; + } + else if (em->i_am_master) + { + if (em->cb_vft.server_stream_accepted_cb) + em->cb_vft.server_stream_accepted_cb (mp, session_index); + em->n_clients_connected++; + } + else + { + if (em->cb_vft.client_stream_accepted_cb) + em->cb_vft.client_stream_accepted_cb (mp, session_index); + em->n_clients_connected++; + } + + if (em->n_clients_connected == em->n_clients * em->n_stream_clients) + { + em->state = STATE_READY; + quic_echo_notify_event (em, ECHO_EVT_LAST_SCONNECTED); + } + if (em->n_quic_clients_connected == em->n_clients) + quic_echo_notify_event (em, ECHO_EVT_LAST_QCONNECTED); +} + +static void +session_connected_handler (session_connected_msg_t * mp) +{ + echo_main_t *em = &echo_main; + echo_session_t *session; + u32 session_index; + svm_fifo_t *rx_fifo, *tx_fifo; + + if (mp->retval) + { + clib_warning ("connection failed with code: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + em->state = STATE_FAILED; + return; + } + + pool_get (em->sessions, session); + clib_memset (session, 0, sizeof (*session)); + session_index = session - em->sessions; + DBG ("CONNECTED session[%lx][0x%lx]", session_index, mp->handle); + + if (wait_for_segment_allocation (mp->segment_handle)) + return; + + rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); + rx_fifo->client_session_index = session_index; + tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); + tx_fifo->client_session_index = session_index; + + session->rx_fifo = rx_fifo; + session->tx_fifo = tx_fifo; + session->vpp_session_handle = mp->handle; + session->session_index = session_index; + session->start = clib_time_now (&em->clib_time); + session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, + svm_msg_q_t *); + + DBG ("Connected session handle %lx, idx %lu RX[%lx] TX[%lx]", mp->handle, + session_index, rx_fifo, tx_fifo); + hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); + + if (mp->context == QUIC_SESSION_TYPE_QUIC) + { + if (em->cb_vft.quic_connected_cb) + em->cb_vft.quic_connected_cb (mp, session_index); + em->n_quic_clients_connected++; + } + else if (em->i_am_master) + { + if (em->cb_vft.server_stream_connected_cb) + em->cb_vft.server_stream_connected_cb (mp, session_index); + em->n_clients_connected++; + } + else + { + if (em->cb_vft.client_stream_connected_cb) + em->cb_vft.client_stream_connected_cb (mp, session_index); + em->n_clients_connected++; + } + + if (em->n_clients_connected == em->n_clients * em->n_stream_clients) + { + em->state = STATE_READY; + quic_echo_notify_event (em, ECHO_EVT_LAST_SCONNECTED); + } + if (em->n_quic_clients_connected == em->n_clients) + quic_echo_notify_event (em, ECHO_EVT_LAST_QCONNECTED); +} + +/* + * + * ECHO Callback definitions + * + */ + + +static void +echo_on_connected_connect (session_connected_msg_t * mp, u32 session_index) +{ + echo_main_t *em = &echo_main; + u8 *uri = format (0, "QUIC://session/%lu", mp->handle); + int i; + + if (!em->first_sconnect_sent) + { + em->first_sconnect_sent = 1; + quic_echo_notify_event (em, ECHO_EVT_FIRST_SCONNECT); + } + for (i = 0; i < em->n_stream_clients; i++) + { + DBG ("CONNECT : new QUIC stream #%d: %s", i, uri); + echo_send_connect (em, uri, QUIC_SESSION_TYPE_STREAM); + } + + clib_warning ("session %u (0x%llx) connected with local ip %U port %d", + session_index, mp->handle, format_ip46_address, &mp->lcl.ip, + mp->lcl.is_ip4, clib_net_to_host_u16 (mp->lcl.port)); +} + +static void +echo_on_connected_send (session_connected_msg_t * mp, u32 session_index) +{ + echo_main_t *em = &echo_main; + int rv; + echo_session_t *session; + + DBG ("Stream Session Connected"); + + session = pool_elt_at_index (em->sessions, session_index); + session->bytes_to_send = em->bytes_to_send; + session->bytes_to_receive = em->bytes_to_receive; + + /* + * Start RX thread + */ + em->thread_args[em->n_clients_connected] = session_index; + rv = pthread_create (&em->client_thread_handles[em->n_clients_connected], + NULL /*attr */ , client_thread_fn, + (void *) &em->thread_args[em->n_clients_connected]); + if (rv) + { + clib_warning ("pthread_create returned %d", rv); + return; + } +} + +static void +echo_on_connected_error (session_connected_msg_t * mp, u32 session_index) +{ + clib_warning ("Got a wrong connected on session %u [%lx]", session_index, + mp->handle); +} + +static void +echo_on_accept_recv (session_accepted_msg_t * mp, u32 session_index) +{ + echo_main_t *em = &echo_main; + int rv; + echo_session_t *session; + + session = pool_elt_at_index (em->sessions, session_index); + session->bytes_to_send = em->bytes_to_send; + session->bytes_to_receive = em->bytes_to_receive; + + DBG ("Stream session accepted 0x%lx, expecting %lu bytes", + session->vpp_session_handle, session->bytes_to_receive); + + /* + * Start RX thread + */ + em->thread_args[em->n_clients_connected] = session_index; + rv = pthread_create (&em->client_thread_handles[em->n_clients_connected], + NULL /*attr */ , client_thread_fn, + (void *) &em->thread_args[em->n_clients_connected]); + if (rv) + { + clib_warning ("pthread_create returned %d", rv); + return; + } + +} + +static void +echo_on_accept_connect (session_accepted_msg_t * mp, u32 session_index) +{ + echo_main_t *em = &echo_main; + DBG ("Accept on QSession index %u", mp->handle); + u8 *uri = format (0, "QUIC://session/%lu", mp->handle); + u32 i; + + if (!em->first_sconnect_sent) + { + em->first_sconnect_sent = 1; + quic_echo_notify_event (em, ECHO_EVT_FIRST_SCONNECT); + } + for (i = 0; i < em->n_stream_clients; i++) + { + DBG ("ACCEPT : new QUIC stream #%d: %s", i, uri); + echo_send_connect (em, uri, QUIC_SESSION_TYPE_STREAM); + } +} + +static void +echo_on_accept_error (session_accepted_msg_t * mp, u32 session_index) +{ + clib_warning ("Got a wrong accept on session %u [%lx]", session_index, + mp->handle); +} + +static void +echo_on_accept_log_ip (session_accepted_msg_t * mp, u32 session_index) +{ + u8 *ip_str; + ip_str = format (0, "%U", format_ip46_address, &mp->rmt.ip, mp->rmt.is_ip4); + clib_warning ("Accepted session from: %s:%d", ip_str, + clib_net_to_host_u16 (mp->rmt.port)); + +} + +static const quic_echo_cb_vft_t default_cb_vft = { + /* Qsessions */ + .quic_accepted_cb = &echo_on_accept_log_ip, + .quic_connected_cb = &echo_on_connected_connect, + /* client initiated streams */ + .server_stream_accepted_cb = NULL, + .client_stream_connected_cb = &echo_on_connected_send, + /* server initiated streams */ + .client_stream_accepted_cb = &echo_on_accept_error, + .server_stream_connected_cb = &echo_on_connected_error, +}; + +static const quic_echo_cb_vft_t server_stream_cb_vft = { + /* Qsessions */ + .quic_accepted_cb = &echo_on_accept_connect, + .quic_connected_cb = NULL, + /* client initiated streams */ + .server_stream_accepted_cb = &echo_on_accept_error, + .client_stream_connected_cb = &echo_on_connected_error, + /* server initiated streams */ + .client_stream_accepted_cb = &echo_on_accept_recv, + .server_stream_connected_cb = &echo_on_connected_send, +}; + +static uword +echo_unformat_quic_setup_vft (unformat_input_t * input, va_list * args) +{ + echo_main_t *em = &echo_main; + if (unformat (input, "serverstream")) + { + clib_warning ("Using QUIC server initiated streams"); + em->no_return = 1; + em->cb_vft = server_stream_cb_vft; + return 1; + } + else if (unformat (input, "default")) + return 1; + return 0; +} + +static uword +echo_unformat_data (unformat_input_t * input, va_list * args) +{ + u64 _a; + u64 *a = va_arg (*args, u64 *); + if (unformat (input, "%lluGb", &_a)) + { + *a = _a << 30; + return 1; + } + else if (unformat (input, "%lluMb", &_a)) + { + *a = _a << 20; + return 1; + } + else if (unformat (input, "%lluKb", &_a)) + { + *a = _a << 10; + return 1; + } + else if (unformat (input, "%llu", a)) + return 1; + return 0; +} + +/* + * + * End of ECHO callback definitions + * + */ + +static void +session_disconnected_handler (session_disconnected_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + session_disconnected_reply_msg_t *rmp; + echo_main_t *em = &echo_main; + echo_session_t *session = 0; + uword *p; + int rv = 0; + DBG ("Disonnected session handle %lx", mp->handle); + p = hash_get (em->session_index_by_vpp_handles, mp->handle); + if (!p) + { + clib_warning ("couldn't find session key %llx", mp->handle); + return; + } + + session = pool_elt_at_index (em->sessions, p[0]); + hash_unset (em->session_index_by_vpp_handles, mp->handle); + + pool_put (em->sessions, session); + + app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, + SESSION_CTRL_EVT_DISCONNECTED_REPLY); + rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data; + rmp->retval = rv; + rmp->handle = mp->handle; + rmp->context = mp->context; + app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); + + session_print_stats (em, session); +} + +static void +session_reset_handler (session_reset_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + echo_main_t *em = &echo_main; + session_reset_reply_msg_t *rmp; + echo_session_t *session = 0; + uword *p; + int rv = 0; + + DBG ("Reset session handle %lx", mp->handle); + p = hash_get (em->session_index_by_vpp_handles, mp->handle); + + if (p) + { + session = pool_elt_at_index (em->sessions, p[0]); + clib_warning ("got reset"); + /* Cleanup later */ + em->time_to_stop = 1; + } + else + { + clib_warning ("couldn't find session key %llx", mp->handle); + return; + } + + app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, + SESSION_CTRL_EVT_RESET_REPLY); + rmp = (session_reset_reply_msg_t *) app_evt->evt->data; + rmp->retval = rv; + rmp->handle = mp->handle; + app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); +} + +static void +handle_mq_event (echo_main_t * em, session_event_t * e, int handle_rx) +{ + switch (e->event_type) + { + case SESSION_CTRL_EVT_BOUND: + DBG ("SESSION_CTRL_EVT_BOUND"); + session_bound_handler ((session_bound_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_ACCEPTED: + DBG ("SESSION_CTRL_EVT_ACCEPTED"); + session_accepted_handler ((session_accepted_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_CONNECTED: + DBG ("SESSION_CTRL_EVT_CONNECTED"); + session_connected_handler ((session_connected_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_DISCONNECTED: + DBG ("SESSION_CTRL_EVT_DISCONNECTED"); + session_disconnected_handler ((session_disconnected_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_RESET: + DBG ("SESSION_CTRL_EVT_RESET"); + session_reset_handler ((session_reset_msg_t *) e->data); + break; + case SESSION_IO_EVT_RX: + DBG ("SESSION_IO_EVT_RX"); + if (handle_rx) + echo_handle_rx (em, e); + break; + default: + clib_warning ("unhandled event %u", e->event_type); + } +} + +static int +clients_run (echo_main_t * em) +{ + svm_msg_q_msg_t msg; + session_event_t *e; + echo_session_t *s; + hash_pair_t *p; + int i; + + /* + * Attach and connect the clients + */ + if (application_attach (em)) + return -1; + + quic_echo_notify_event (em, ECHO_EVT_FIRST_QCONNECT); + for (i = 0; i < em->n_clients; i++) + echo_send_connect (em, em->uri, QUIC_SESSION_TYPE_QUIC); + + wait_for_state_change (em, STATE_READY, TIMEOUT); + + /* + * Wait for client threads to send the data + */ + DBG ("Waiting for data on %u clients", em->n_clients_connected); + while (em->n_clients_connected) + { + if (svm_msg_q_is_empty (em->our_event_queue)) + continue; + if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_TIMEDWAIT, 1)) + continue; + e = svm_msg_q_msg_data (em->our_event_queue, &msg); + handle_mq_event (em, e, 0 /* handle_rx */ ); + svm_msg_q_free_msg (em->our_event_queue, &msg); + } + + /* *INDENT-OFF* */ + hash_foreach_pair (p, em->session_index_by_vpp_handles, + ({ + s = pool_elt_at_index (em->sessions, p->value[0]); + DBG ("Sending disconnect on session %lu", p->key); + client_disconnect_session (em, s); + })); + /* *INDENT-ON* */ + + wait_for_disconnected_sessions (em); + application_detach (em); + return 0; +} + +static void +vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp) +{ + echo_main_t *em = &echo_main; + if (mp->retval) + { + clib_warning ("bind failed: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + em->state = STATE_FAILED; + return; + } + + em->state = STATE_LISTEN; +} + +static void +vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp) +{ + echo_main_t *em = &echo_main; + + if (mp->retval != 0) + clib_warning ("returned %d", ntohl (mp->retval)); + + em->state = STATE_START; +} + +u8 * +format_ip4_address (u8 * s, va_list * args) +{ + u8 *a = va_arg (*args, u8 *); + return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); +} + +u8 * +format_ip6_address (u8 * s, va_list * args) +{ + ip6_address_t *a = va_arg (*args, ip6_address_t *); + u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon; + + i_max_n_zero = ARRAY_LEN (a->as_u16); + max_n_zeros = 0; + i_first_zero = i_max_n_zero; + n_zeros = 0; + for (i = 0; i < ARRAY_LEN (a->as_u16); i++) + { + u32 is_zero = a->as_u16[i] == 0; + if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16)) + { + i_first_zero = i; + n_zeros = 0; + } + n_zeros += is_zero; + if ((!is_zero && n_zeros > max_n_zeros) + || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros)) + { + i_max_n_zero = i_first_zero; + max_n_zeros = n_zeros; + i_first_zero = ARRAY_LEN (a->as_u16); + n_zeros = 0; + } + } + + last_double_colon = 0; + for (i = 0; i < ARRAY_LEN (a->as_u16); i++) + { + if (i == i_max_n_zero && max_n_zeros > 1) + { + s = format (s, "::"); + i += max_n_zeros - 1; + last_double_colon = 1; + } + else + { + s = format (s, "%s%x", + (last_double_colon || i == 0) ? "" : ":", + clib_net_to_host_u16 (a->as_u16[i])); + last_double_colon = 0; + } + } + + return s; +} + +/* Format an IP46 address. */ +u8 * +format_ip46_address (u8 * s, va_list * args) +{ + ip46_address_t *ip46 = va_arg (*args, ip46_address_t *); + ip46_type_t type = va_arg (*args, ip46_type_t); + int is_ip4 = 1; + + switch (type) + { + case IP46_TYPE_ANY: + is_ip4 = ip46_address_is_ip4 (ip46); + break; + case IP46_TYPE_IP4: + is_ip4 = 1; + break; + case IP46_TYPE_IP6: + is_ip4 = 0; + break; + } + + return is_ip4 ? + format (s, "%U", format_ip4_address, &ip46->ip4) : + format (s, "%U", format_ip6_address, &ip46->ip6); +} + +static void +echo_handle_rx (echo_main_t * em, session_event_t * e) +{ + int n_read, max_dequeue, n_sent; + u32 offset, to_dequeue; + echo_session_t *s; + s = pool_elt_at_index (em->sessions, e->session_index); + + /* Clear event only once. Otherwise, if we do it in the loop by calling + * app_recv_stream, we may end up with a lot of unhandled rx events on the + * message queue */ + svm_fifo_unset_event (s->rx_fifo); + max_dequeue = svm_fifo_max_dequeue (s->rx_fifo); + if (PREDICT_FALSE (!max_dequeue)) + return; + do + { + /* The options here are to limit ourselves to max_dequeue or read + * even the data that was enqueued while we were dequeueing and which + * now has an rx event in the mq. Either of the two work. */ + to_dequeue = clib_min (max_dequeue, vec_len (em->rx_buf)); + n_read = app_recv_stream_raw (s->rx_fifo, em->rx_buf, to_dequeue, + 0 /* clear evt */ , 0 /* peek */ ); + + if (n_read <= 0) + break; + DBG ("Notify cause %u bytes", n_read); + notify_rx_data_to_vpp (s); + if (em->test_return_packets) + test_recv_bytes (em, s, em->rx_buf, n_read); + + max_dequeue -= n_read; + s->bytes_received += n_read; + s->bytes_to_receive -= n_read; + + /* Reflect if a non-drop session */ + if (!em->no_return) + { + offset = 0; + do + { + n_sent = app_send_stream ((app_session_t *) s, + em->rx_buf + offset, + n_read, SVM_Q_WAIT); + if (n_sent <= 0) + continue; + n_read -= n_sent; + s->bytes_to_send -= n_sent; + s->bytes_sent += n_sent; + offset += n_sent; + } + while (n_read > 0); + } + } + while (max_dequeue > 0 && !em->time_to_stop); +} + +static void +server_handle_mq (echo_main_t * em) +{ + svm_msg_q_msg_t msg; + session_event_t *e; + + while (1) + { + int rc = svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_TIMEDWAIT, 1); + if (PREDICT_FALSE (rc == ETIMEDOUT && em->time_to_stop)) + break; + if (rc == ETIMEDOUT) + continue; + e = svm_msg_q_msg_data (em->our_event_queue, &msg); + handle_mq_event (em, e, em->state == STATE_READY /* handle_rx */ ); + svm_msg_q_free_msg (em->our_event_queue, &msg); + } +} + +static void +server_send_listen (echo_main_t * em) +{ + vl_api_bind_uri_t *bmp; + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_BIND_URI); + bmp->client_index = em->my_client_index; + bmp->context = ntohl (0xfeedface); + memcpy (bmp->uri, em->uri, vec_len (em->uri)); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); +} + +static void +server_send_unbind (echo_main_t * em) +{ + vl_api_unbind_uri_t *ump; + + ump = vl_msg_api_alloc (sizeof (*ump)); + clib_memset (ump, 0, sizeof (*ump)); + + ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI); + ump->client_index = em->my_client_index; + memcpy (ump->uri, em->uri, vec_len (em->uri)); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & ump); +} + +static int +server_run (echo_main_t * em) +{ + echo_session_t *session; + int i; + + /* $$$$ hack preallocation */ + for (i = 0; i < 200000; i++) + { + pool_get (em->sessions, session); + clib_memset (session, 0, sizeof (*session)); + } + for (i = 0; i < 200000; i++) + pool_put_index (em->sessions, i); + + if (application_attach (em)) + return -1; + + /* Bind to uri */ + server_send_listen (em); + if (wait_for_state_change (em, STATE_READY, 0)) + return -2; + + /* Enter handle event loop */ + server_handle_mq (em); + + /* Cleanup */ + server_send_unbind (em); + application_detach (em); + fformat (stdout, "Test complete...\n"); + return 0; +} + +static void +vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t * + mp) +{ + echo_main_t *em = &echo_main; + uword *p; + DBG ("Got disonnected reply for session handle %lu", mp->handle); + em->state = STATE_START; + + p = hash_get (em->session_index_by_vpp_handles, mp->handle); + if (p) + hash_unset (em->session_index_by_vpp_handles, mp->handle); + else + clib_warning ("couldn't find session key %llx", mp->handle); + + if (mp->retval) + clib_warning ("vpp complained about disconnect: %d", ntohl (mp->retval)); +} + +static void + vl_api_application_tls_cert_add_reply_t_handler + (vl_api_application_tls_cert_add_reply_t * mp) +{ + if (mp->retval) + clib_warning ("failed to add tls cert"); +} + +static void + vl_api_application_tls_key_add_reply_t_handler + (vl_api_application_tls_key_add_reply_t * mp) +{ + if (mp->retval) + clib_warning ("failed to add tls key"); +} + +#define foreach_quic_echo_msg \ +_(BIND_URI_REPLY, bind_uri_reply) \ +_(UNBIND_URI_REPLY, unbind_uri_reply) \ +_(DISCONNECT_SESSION_REPLY, disconnect_session_reply) \ +_(APPLICATION_ATTACH_REPLY, application_attach_reply) \ +_(APPLICATION_DETACH_REPLY, application_detach_reply) \ +_(MAP_ANOTHER_SEGMENT, map_another_segment) \ +_(APPLICATION_TLS_CERT_ADD_REPLY, application_tls_cert_add_reply) \ +_(APPLICATION_TLS_KEY_ADD_REPLY, application_tls_key_add_reply) \ + +void +quic_echo_api_hookup (echo_main_t * em) +{ +#define _(N,n) \ + vl_msg_api_set_handlers(VL_API_##N, #n, \ + vl_api_##n##_t_handler, \ + vl_noop_handler, \ + vl_api_##n##_t_endian, \ + vl_api_##n##_t_print, \ + sizeof(vl_api_##n##_t), 1); + foreach_quic_echo_msg; +#undef _ +} + +static void +print_usage_and_exit (void) +{ + fprintf (stderr, + "quic_echo [socket-name SOCKET] [client|server] [uri URI] [OPTIONS]\n" + "\n" + " socket-name PATH Specify the binary socket path to connect to VPP\n" + " use-svm-api Use SVM API to connect to VPP\n" + " test-bytes[:assert] Check data correctness when receiving (assert fails on first error)\n" + " fifo-size N Use N Kb fifos\n" + " appns NAMESPACE Use the namespace NAMESPACE\n" + " all-scope all-scope option\n" + " local-scope local-scope option\n" + " global-scope global-scope option\n" + " secret SECRET set namespace secret\n" + " chroot prefix PATH Use PATH as memory root path\n" + " quic-setup OPT OPT=serverstream : Client open N connections. On each one server opens M streams\n" + " by default : Client open N connections. On each one client opens M streams\n" + "\n" + " no-return Drop the data when received, dont reply\n" + " nclients N[/M] Open N QUIC connections, each one with M streams (M defaults to 1)\n" + " send N[Kb|Mb|GB] Send N [K|M|G]bytes\n" + " recv N[Kb|Mb|GB] Expect N [K|M|G]bytes\n" + " nclients N[/M] Open N QUIC connections, each one with M streams (M defaults to 1)\n"); + exit (1); +} + + +void +quic_echo_process_opts (int argc, char **argv) +{ + echo_main_t *em = &echo_main; + unformat_input_t _argv, *a = &_argv; + u32 tmp; + u8 *chroot_prefix; + u8 *uri = 0; + + unformat_init_command_line (a, argv); + while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT) + { + if (unformat (a, "chroot prefix %s", &chroot_prefix)) + { + vl_set_memory_root_path ((char *) chroot_prefix); + } + else if (unformat (a, "uri %s", &uri)) + em->uri = format (0, "%s%c", uri, 0); + else if (unformat (a, "server")) + em->i_am_master = 1; + else if (unformat (a, "client")) + em->i_am_master = 0; + else if (unformat (a, "no-return")) + em->no_return = 1; + else if (unformat (a, "test-bytes:assert")) + em->test_return_packets = RETURN_PACKETS_ASSERT; + else if (unformat (a, "test-bytes")) + em->test_return_packets = RETURN_PACKETS_LOG_WRONG; + else if (unformat (a, "socket-name %s", &em->socket_name)) + ; + else if (unformat (a, "use-svm-api")) + em->use_sock_api = 0; + else if (unformat (a, "fifo-size %d", &tmp)) + em->fifo_size = tmp << 10; + else + if (unformat + (a, "nclients %d/%d", &em->n_clients, &em->n_stream_clients)) + ; + else if (unformat (a, "nclients %d", &em->n_clients)) + ; + else if (unformat (a, "appns %_%v%_", &em->appns_id)) + ; + else if (unformat (a, "all-scope")) + em->appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE + | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE); + else if (unformat (a, "local-scope")) + em->appns_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE; + else if (unformat (a, "global-scope")) + em->appns_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE; + else if (unformat (a, "secret %lu", &em->appns_secret)) + ; + else if (unformat (a, "quic-setup %U", echo_unformat_quic_setup_vft)) + ; + else + if (unformat (a, "send %U", echo_unformat_data, &em->bytes_to_send)) + ; + else + if (unformat + (a, "recv %U", echo_unformat_data, &em->bytes_to_receive)) + ; + else if (unformat (a, "time %U:%U", + echo_unformat_timing_event, &em->timing_start_event, + echo_unformat_timing_event, &em->timing_end_event)) + ; + else + print_usage_and_exit (); + } +} + +int +main (int argc, char **argv) +{ + echo_main_t *em = &echo_main; + fifo_segment_main_t *sm = &em->segment_main; + char *app_name; + int i, rv; + u32 n_clients; + + clib_mem_init_thread_safe (0, 256 << 20); + clib_memset (em, 0, sizeof (*em)); + em->session_index_by_vpp_handles = hash_create (0, sizeof (uword)); + em->shared_segment_handles = hash_create (0, sizeof (uword)); + em->my_pid = getpid (); + em->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0); + em->use_sock_api = 1; + em->fifo_size = 64 << 10; + em->n_clients = 1; + em->n_stream_clients = 1; + em->max_test_msg = 50; + em->time_to_stop = 0; + em->i_am_master = 1; + em->test_return_packets = RETURN_PACKETS_NOTEST; + em->timing_start_event = ECHO_EVT_FIRST_QCONNECT; + em->timing_end_event = ECHO_EVT_LAST_BYTE; + em->bytes_to_receive = 64 << 10; + em->bytes_to_send = 64 << 10; + em->uri = format (0, "%s%c", "quic://0.0.0.0/1234", 0); + em->cb_vft = default_cb_vft; + quic_echo_process_opts (argc, argv); + + n_clients = em->n_clients * em->n_stream_clients; + vec_validate (em->client_thread_handles, n_clients - 1); + vec_validate (em->thread_args, n_clients - 1); + clib_time_init (&em->clib_time); + init_error_string_table (em); + fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20); + clib_spinlock_init (&em->segment_handles_lock); + vec_validate (em->rx_buf, 4 << 20); + vec_validate (em->connect_test_data, 1024 * 1024 - 1); + for (i = 0; i < vec_len (em->connect_test_data); i++) + em->connect_test_data[i] = i & 0xff; + + setup_signal_handlers (); + quic_echo_api_hookup (em); + + app_name = em->i_am_master ? "quic_echo_server" : "quic_echo_client"; + if (connect_to_vpp (app_name) < 0) + { + svm_region_exit (); + fformat (stderr, "Couldn't connect to vpe, exiting...\n"); + exit (1); + } + + quic_echo_notify_event (em, ECHO_EVT_START); + if (em->i_am_master) + rv = server_run (em); + else + rv = clients_run (em); + if (rv) + exit (rv); + quic_echo_notify_event (em, ECHO_EVT_EXIT); + print_global_stats (em); + + /* Make sure detach finishes */ + if (wait_for_state_change (em, STATE_DETACHED, TIMEOUT)) + exit (-1); + disconnect_from_vpp (em); + exit (0); +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/src/plugins/hs_apps/sapi/tcp_echo.c b/src/plugins/hs_apps/sapi/tcp_echo.c new file mode 100644 index 00000000000..6c3ce928490 --- /dev/null +++ b/src/plugins/hs_apps/sapi/tcp_echo.c @@ -0,0 +1,1414 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include +#include + +#define vl_typedefs /* define message structures */ +#include +#undef vl_typedefs + +/* declare message handlers for each api */ + +#define vl_endianfun /* define message structures */ +#include +#undef vl_endianfun + +/* instantiate all the print functions we know about */ +#define vl_print(handle, ...) +#define vl_printfun +#include +#undef vl_printfun + +#define TCP_ECHO_DBG 0 +#define DBG(_fmt,_args...) \ + if (TCP_ECHO_DBG) \ + clib_warning (_fmt, _args) + +typedef struct +{ + CLIB_CACHE_LINE_ALIGN_MARK (cacheline0); +#define _(type, name) type name; + foreach_app_session_field +#undef _ + u64 vpp_session_handle; + u64 bytes_sent; + u64 bytes_to_send; + volatile u64 bytes_received; + volatile u64 bytes_to_receive; + f64 start; +} echo_session_t; + +typedef enum +{ + STATE_START, + STATE_ATTACHED, + STATE_LISTEN, + STATE_READY, + STATE_DISCONNECTING, + STATE_FAILED, + STATE_DETACHED +} connection_state_t; + +typedef struct +{ + /* vpe input queue */ + svm_queue_t *vl_input_queue; + + /* API client handle */ + u32 my_client_index; + + /* The URI we're playing with */ + u8 *uri; + + /* Session pool */ + echo_session_t *sessions; + + /* Hash table for disconnect processing */ + uword *session_index_by_vpp_handles; + + /* intermediate rx buffer */ + u8 *rx_buf; + + /* URI for slave's connect */ + u8 *connect_uri; + + u32 connected_session_index; + + int i_am_master; + + /* drop all packets */ + int no_return; + + /* Our event queue */ + svm_msg_q_t *our_event_queue; + + u8 *socket_name; + + pid_t my_pid; + + /* For deadman timers */ + clib_time_t clib_time; + + /* State of the connection, shared between msg RX thread and main thread */ + volatile connection_state_t state; + + /* Signal variables */ + volatile int time_to_stop; + volatile int time_to_print_stats; + + u32 configured_segment_size; + + /* VNET_API_ERROR_FOO -> "Foo" hash table */ + uword *error_string_by_error_number; + + u8 *connect_test_data; + pthread_t *client_thread_handles; + u32 *thread_args; + u32 client_bytes_received; + u8 test_return_packets; + u64 bytes_to_send; + u32 fifo_size; + + u32 n_clients; + u64 tx_total; + u64 rx_total; + + volatile u32 n_clients_connected; + volatile u32 n_active_clients; + + + /** Flag that decides if socket, instead of svm, api is used to connect to + * vpp. If sock api is used, shm binary api is subsequently bootstrapped + * and all other messages are exchanged using shm IPC. */ + u8 use_sock_api; + + fifo_segment_main_t segment_main; +} echo_main_t; + +echo_main_t echo_main; + +#if CLIB_DEBUG > 0 +#define NITER 10000 +#else +#define NITER 4000000 +#endif + +static u8 * +format_api_error (u8 * s, va_list * args) +{ + echo_main_t *em = &echo_main; + i32 error = va_arg (*args, u32); + uword *p; + + p = hash_get (em->error_string_by_error_number, -error); + + if (p) + s = format (s, "%s", p[0]); + else + s = format (s, "%d", error); + return s; +} + +static void +init_error_string_table (echo_main_t * em) +{ + em->error_string_by_error_number = hash_create (0, sizeof (uword)); + +#define _(n,v,s) hash_set (em->error_string_by_error_number, -v, s); + foreach_vnet_api_error; +#undef _ + + hash_set (em->error_string_by_error_number, 99, "Misc"); +} + +static void handle_mq_event (session_event_t * e); + +static int +wait_for_state_change (echo_main_t * em, connection_state_t state) +{ + svm_msg_q_msg_t msg; + session_event_t *e; + f64 timeout; + +#if CLIB_DEBUG > 0 +#define TIMEOUT 600.0 +#else +#define TIMEOUT 600.0 +#endif + + timeout = clib_time_now (&em->clib_time) + TIMEOUT; + + while (clib_time_now (&em->clib_time) < timeout) + { + if (em->state == state) + return 0; + if (em->state == STATE_FAILED) + return -1; + if (em->time_to_stop == 1) + return 0; + if (!em->our_event_queue || em->state < STATE_ATTACHED) + continue; + + if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_NOWAIT, 0)) + continue; + e = svm_msg_q_msg_data (em->our_event_queue, &msg); + handle_mq_event (e); + svm_msg_q_free_msg (em->our_event_queue, &msg); + } + clib_warning ("timeout waiting for state %d", state); + return -1; +} + +void +application_send_attach (echo_main_t * em) +{ + vl_api_application_attach_t *bmp; + vl_api_application_tls_cert_add_t *cert_mp; + vl_api_application_tls_key_add_t *key_mp; + + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH); + bmp->client_index = em->my_client_index; + bmp->context = ntohl (0xfeedface); + bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ACCEPT_REDIRECT; + bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_ADD_SEGMENT; + bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 16; + bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = em->fifo_size; + bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = em->fifo_size; + bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20; + bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20; + bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 256; + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); + + cert_mp = vl_msg_api_alloc (sizeof (*cert_mp) + test_srv_crt_rsa_len); + clib_memset (cert_mp, 0, sizeof (*cert_mp)); + cert_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_CERT_ADD); + cert_mp->client_index = em->my_client_index; + cert_mp->context = ntohl (0xfeedface); + cert_mp->cert_len = clib_host_to_net_u16 (test_srv_crt_rsa_len); + clib_memcpy_fast (cert_mp->cert, test_srv_crt_rsa, test_srv_crt_rsa_len); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cert_mp); + + key_mp = vl_msg_api_alloc (sizeof (*key_mp) + test_srv_key_rsa_len); + clib_memset (key_mp, 0, sizeof (*key_mp) + test_srv_key_rsa_len); + key_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_KEY_ADD); + key_mp->client_index = em->my_client_index; + key_mp->context = ntohl (0xfeedface); + key_mp->key_len = clib_host_to_net_u16 (test_srv_key_rsa_len); + clib_memcpy_fast (key_mp->key, test_srv_key_rsa, test_srv_key_rsa_len); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & key_mp); +} + +static int +application_attach (echo_main_t * em) +{ + application_send_attach (em); + if (wait_for_state_change (em, STATE_ATTACHED)) + { + clib_warning ("timeout waiting for STATE_ATTACHED"); + return -1; + } + return 0; +} + +void +application_detach (echo_main_t * em) +{ + vl_api_application_detach_t *bmp; + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH); + bmp->client_index = em->my_client_index; + bmp->context = ntohl (0xfeedface); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); + + DBG ("%s", "Sent detach"); +} + +static int +ssvm_segment_attach (char *name, ssvm_segment_type_t type, int fd) +{ + fifo_segment_create_args_t _a, *a = &_a; + fifo_segment_main_t *sm = &echo_main.segment_main; + int rv; + + clib_memset (a, 0, sizeof (*a)); + a->segment_name = (char *) name; + a->segment_type = type; + + if (type == SSVM_SEGMENT_MEMFD) + a->memfd_fd = fd; + + if ((rv = fifo_segment_attach (sm, a))) + { + clib_warning ("svm_fifo_segment_attach ('%s') failed", name); + return rv; + } + + vec_reset_length (a->new_segment_indices); + return 0; +} + +static void +vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t * + mp) +{ + echo_main_t *em = &echo_main; + int *fds = 0; + u32 n_fds = 0; + + if (mp->retval) + { + clib_warning ("attach failed: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + goto failed; + } + + if (mp->segment_name_length == 0) + { + clib_warning ("segment_name_length zero"); + goto failed; + } + + ASSERT (mp->app_event_queue_address); + em->our_event_queue = uword_to_pointer (mp->app_event_queue_address, + svm_msg_q_t *); + + if (mp->n_fds) + { + vec_validate (fds, mp->n_fds); + vl_socket_client_recv_fd_msg (fds, mp->n_fds, 5); + + if (mp->fd_flags & SESSION_FD_F_VPP_MQ_SEGMENT) + if (ssvm_segment_attach (0, SSVM_SEGMENT_MEMFD, fds[n_fds++])) + goto failed; + + if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT) + if (ssvm_segment_attach ((char *) mp->segment_name, + SSVM_SEGMENT_MEMFD, fds[n_fds++])) + goto failed; + + if (mp->fd_flags & SESSION_FD_F_MQ_EVENTFD) + svm_msg_q_set_consumer_eventfd (em->our_event_queue, fds[n_fds++]); + + vec_free (fds); + } + else + { + if (ssvm_segment_attach ((char *) mp->segment_name, SSVM_SEGMENT_SHM, + -1)) + goto failed; + } + + em->state = STATE_ATTACHED; + return; +failed: + em->state = STATE_FAILED; + return; +} + +static void +vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t * + mp) +{ + if (mp->retval) + clib_warning ("detach returned with err: %d", mp->retval); + echo_main.state = STATE_DETACHED; +} + +static void +stop_signal (int signum) +{ + echo_main_t *um = &echo_main; + + um->time_to_stop = 1; +} + +static void +stats_signal (int signum) +{ + echo_main_t *um = &echo_main; + + um->time_to_print_stats = 1; +} + +static clib_error_t * +setup_signal_handlers (void) +{ + signal (SIGINT, stats_signal); + signal (SIGQUIT, stop_signal); + signal (SIGTERM, stop_signal); + + return 0; +} + +void +vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...) +{ + clib_warning ("BUG"); +} + +int +connect_to_vpp (char *name) +{ + echo_main_t *em = &echo_main; + api_main_t *am = &api_main; + + if (em->use_sock_api) + { + if (vl_socket_client_connect ((char *) em->socket_name, name, + 0 /* default rx, tx buffer */ )) + { + clib_warning ("socket connect failed"); + return -1; + } + + if (vl_socket_client_init_shm (0, 1 /* want_pthread */ )) + { + clib_warning ("init shm api failed"); + return -1; + } + } + else + { + if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0) + { + clib_warning ("shmem connect failed"); + return -1; + } + } + em->vl_input_queue = am->shmem_hdr->vl_input_queue; + em->my_client_index = am->my_client_index; + return 0; +} + +void +disconnect_from_vpp (echo_main_t * em) +{ + if (em->use_sock_api) + vl_socket_client_disconnect (); + else + vl_client_disconnect_from_vlib (); +} + +static void +vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp) +{ + fifo_segment_main_t *sm = &echo_main.segment_main; + fifo_segment_create_args_t _a, *a = &_a; + int rv; + + clib_memset (a, 0, sizeof (*a)); + a->segment_name = (char *) mp->segment_name; + a->segment_size = mp->segment_size; + /* Attach to the segment vpp created */ + rv = fifo_segment_attach (sm, a); + if (rv) + { + clib_warning ("svm_fifo_segment_attach ('%s') failed", + mp->segment_name); + return; + } + clib_warning ("Mapped new segment '%s' size %d", mp->segment_name, + mp->segment_size); +} + +static void +session_print_stats (echo_main_t * em, echo_session_t * session) +{ + f64 deltat; + u64 bytes; + + deltat = clib_time_now (&em->clib_time) - session->start; + bytes = em->i_am_master ? session->bytes_received : em->bytes_to_send; + fformat (stdout, "Finished in %.6f\n", deltat); + fformat (stdout, "%.4f Gbit/second\n", (bytes * 8.0) / deltat / 1e9); +} + +static void +test_recv_bytes (echo_session_t * s, u8 * rx_buf, u32 n_read) +{ + int i; + for (i = 0; i < n_read; i++) + { + if (rx_buf[i] != ((s->bytes_received + i) & 0xff)) + { + clib_warning ("error at byte %lld, 0x%x not 0x%x", + s->bytes_received + i, rx_buf[i], + ((s->bytes_received + i) & 0xff)); + } + } +} + +static void +recv_data_chunk (echo_main_t * em, echo_session_t * s, u8 * rx_buf) +{ + int n_to_read, n_read; + + n_to_read = svm_fifo_max_dequeue_cons (s->rx_fifo); + if (!n_to_read) + return; + + do + { + n_read = app_recv_stream ((app_session_t *) s, rx_buf, + vec_len (rx_buf)); + + if (n_read > 0) + { + if (em->test_return_packets) + test_recv_bytes (s, rx_buf, n_read); + + n_to_read -= n_read; + + s->bytes_received += n_read; + s->bytes_to_receive -= n_read; + } + else + break; + } + while (n_to_read > 0); +} + +static void +send_data_chunk (echo_main_t * em, echo_session_t * s) +{ + u64 test_buf_len, bytes_this_chunk, test_buf_offset; + u8 *test_data = em->connect_test_data; + int n_sent; + + test_buf_len = vec_len (test_data); + test_buf_offset = s->bytes_sent % test_buf_len; + bytes_this_chunk = clib_min (test_buf_len - test_buf_offset, + s->bytes_to_send); + + n_sent = app_send_stream ((app_session_t *) s, test_data + test_buf_offset, + bytes_this_chunk, 0); + + if (n_sent > 0) + { + s->bytes_to_send -= n_sent; + s->bytes_sent += n_sent; + } +} + +/* + * Rx/Tx polling thread per connection + */ +static void * +client_thread_fn (void *arg) +{ + echo_main_t *em = &echo_main; + static u8 *rx_buf = 0; + u32 session_index = *(u32 *) arg; + echo_session_t *s; + + vec_validate (rx_buf, 1 << 20); + + while (!em->time_to_stop && em->state != STATE_READY) + ; + + s = pool_elt_at_index (em->sessions, session_index); + while (!em->time_to_stop) + { + send_data_chunk (em, s); + recv_data_chunk (em, s, rx_buf); + if (!s->bytes_to_send && !s->bytes_to_receive) + break; + } + + DBG ("session %d done", session_index); + em->tx_total += s->bytes_sent; + em->rx_total += s->bytes_received; + em->n_active_clients--; + + pthread_exit (0); +} + +void +client_send_connect (echo_main_t * em) +{ + vl_api_connect_uri_t *cmp; + cmp = vl_msg_api_alloc (sizeof (*cmp)); + clib_memset (cmp, 0, sizeof (*cmp)); + + cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI); + cmp->client_index = em->my_client_index; + cmp->context = ntohl (0xfeedface); + memcpy (cmp->uri, em->connect_uri, vec_len (em->connect_uri)); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cmp); +} + +void +client_send_disconnect (echo_main_t * em, echo_session_t * s) +{ + vl_api_disconnect_session_t *dmp; + dmp = vl_msg_api_alloc (sizeof (*dmp)); + clib_memset (dmp, 0, sizeof (*dmp)); + dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION); + dmp->client_index = em->my_client_index; + dmp->handle = s->vpp_session_handle; + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & dmp); +} + +int +client_disconnect (echo_main_t * em, echo_session_t * s) +{ + client_send_disconnect (em, s); + pool_put (em->sessions, s); + clib_memset (s, 0xfe, sizeof (*s)); + return 0; +} + +static void +session_bound_handler (session_bound_msg_t * mp) +{ + echo_main_t *em = &echo_main; + + if (mp->retval) + { + clib_warning ("bind failed: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + em->state = STATE_FAILED; + return; + } + + clib_warning ("listening on %U:%u", format_ip46_address, mp->lcl_ip, + mp->lcl_is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6, mp->lcl_port); + em->state = STATE_READY; +} + +static void +session_accepted_handler (session_accepted_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + session_accepted_reply_msg_t *rmp; + svm_fifo_t *rx_fifo, *tx_fifo; + echo_main_t *em = &echo_main; + echo_session_t *session; + static f64 start_time; + u32 session_index; + u8 *ip_str; + + if (start_time == 0.0) + start_time = clib_time_now (&em->clib_time); + + ip_str = format (0, "%U", format_ip46_address, &mp->rmt.ip, mp->rmt.is_ip4); + clib_warning ("Accepted session from: %s:%d", ip_str, + clib_net_to_host_u16 (mp->rmt.port)); + + /* Allocate local session and set it up */ + pool_get (em->sessions, session); + session_index = session - em->sessions; + + rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); + rx_fifo->client_session_index = session_index; + tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); + tx_fifo->client_session_index = session_index; + + session->rx_fifo = rx_fifo; + session->tx_fifo = tx_fifo; + session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, + svm_msg_q_t *); + + /* Add it to lookup table */ + hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); + + em->state = STATE_READY; + + /* Stats printing */ + if (pool_elts (em->sessions) && (pool_elts (em->sessions) % 20000) == 0) + { + f64 now = clib_time_now (&em->clib_time); + fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n", + pool_elts (em->sessions), now - start_time, + (f64) pool_elts (em->sessions) / (now - start_time)); + } + + /* + * Send accept reply to vpp + */ + app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, + SESSION_CTRL_EVT_ACCEPTED_REPLY); + rmp = (session_accepted_reply_msg_t *) app_evt->evt->data; + rmp->handle = mp->handle; + rmp->context = mp->context; + app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); + + session->bytes_received = 0; + session->start = clib_time_now (&em->clib_time); +} + +static void +session_connected_handler (session_connected_msg_t * mp) +{ + echo_main_t *em = &echo_main; + echo_session_t *session; + u32 session_index; + svm_fifo_t *rx_fifo, *tx_fifo; + int rv; + + if (mp->retval) + { + clib_warning ("connection failed with code: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + em->state = STATE_FAILED; + return; + } + + /* + * Setup session + */ + + pool_get (em->sessions, session); + clib_memset (session, 0, sizeof (*session)); + session_index = session - em->sessions; + + rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); + rx_fifo->client_session_index = session_index; + tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); + tx_fifo->client_session_index = session_index; + + session->rx_fifo = rx_fifo; + session->tx_fifo = tx_fifo; + session->vpp_session_handle = mp->handle; + session->start = clib_time_now (&em->clib_time); + session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, + svm_msg_q_t *); + + hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); + + /* + * Start RX thread + */ + em->thread_args[em->n_clients_connected] = session_index; + rv = pthread_create (&em->client_thread_handles[em->n_clients_connected], + NULL /*attr */ , client_thread_fn, + (void *) &em->thread_args[em->n_clients_connected]); + if (rv) + { + clib_warning ("pthread_create returned %d", rv); + return; + } + + em->n_clients_connected += 1; + clib_warning ("session %u (0x%llx) connected with local ip %U port %d", + session_index, mp->handle, format_ip46_address, &mp->lcl.ip, + mp->lcl.is_ip4, clib_net_to_host_u16 (mp->lcl.port)); +} + +static void +session_disconnected_handler (session_disconnected_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + session_disconnected_reply_msg_t *rmp; + echo_main_t *em = &echo_main; + echo_session_t *session = 0; + uword *p; + int rv = 0; + + p = hash_get (em->session_index_by_vpp_handles, mp->handle); + if (!p) + { + clib_warning ("couldn't find session key %llx", mp->handle); + return; + } + + session = pool_elt_at_index (em->sessions, p[0]); + hash_unset (em->session_index_by_vpp_handles, mp->handle); + pool_put (em->sessions, session); + + app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, + SESSION_CTRL_EVT_DISCONNECTED_REPLY); + rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data; + rmp->retval = rv; + rmp->handle = mp->handle; + rmp->context = mp->context; + app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); + + session_print_stats (em, session); +} + +static void +session_reset_handler (session_reset_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + echo_main_t *em = &echo_main; + session_reset_reply_msg_t *rmp; + echo_session_t *session = 0; + uword *p; + int rv = 0; + + p = hash_get (em->session_index_by_vpp_handles, mp->handle); + + if (p) + { + session = pool_elt_at_index (em->sessions, p[0]); + clib_warning ("got reset"); + /* Cleanup later */ + em->time_to_stop = 1; + } + else + { + clib_warning ("couldn't find session key %llx", mp->handle); + return; + } + + app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, + SESSION_CTRL_EVT_RESET_REPLY); + rmp = (session_reset_reply_msg_t *) app_evt->evt->data; + rmp->retval = rv; + rmp->handle = mp->handle; + app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); +} + +static void +handle_mq_event (session_event_t * e) +{ + switch (e->event_type) + { + case SESSION_CTRL_EVT_BOUND: + session_bound_handler ((session_bound_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_ACCEPTED: + session_accepted_handler ((session_accepted_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_CONNECTED: + session_connected_handler ((session_connected_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_DISCONNECTED: + session_disconnected_handler ((session_disconnected_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_RESET: + session_reset_handler ((session_reset_msg_t *) e->data); + break; + default: + clib_warning ("unhandled %u", e->event_type); + } +} + +static void +clients_run (echo_main_t * em) +{ + f64 start_time, deltat, timeout = 100.0; + svm_msg_q_msg_t msg; + session_event_t *e; + echo_session_t *s; + int i; + + /* Init test data */ + vec_validate (em->connect_test_data, 1024 * 1024 - 1); + for (i = 0; i < vec_len (em->connect_test_data); i++) + em->connect_test_data[i] = i & 0xff; + + /* + * Attach and connect the clients + */ + if (application_attach (em)) + return; + + for (i = 0; i < em->n_clients; i++) + client_send_connect (em); + + start_time = clib_time_now (&em->clib_time); + while (em->n_clients_connected < em->n_clients + && (clib_time_now (&em->clib_time) - start_time < timeout) + && em->state != STATE_FAILED) + + { + svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_WAIT, 0); + e = svm_msg_q_msg_data (em->our_event_queue, &msg); + handle_mq_event (e); + svm_msg_q_free_msg (em->our_event_queue, &msg); + } + + if (em->n_clients_connected != em->n_clients) + { + clib_warning ("failed to initialize all connections"); + return; + } + + /* + * Initialize connections + */ + for (i = 0; i < em->n_clients; i++) + { + s = pool_elt_at_index (em->sessions, i); + s->bytes_to_send = em->bytes_to_send; + if (!em->no_return) + s->bytes_to_receive = em->bytes_to_send; + } + em->n_active_clients = em->n_clients_connected; + + /* + * Wait for client threads to send the data + */ + start_time = clib_time_now (&em->clib_time); + em->state = STATE_READY; + while (em->n_active_clients) + if (!svm_msg_q_is_empty (em->our_event_queue)) + { + if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_WAIT, 0)) + { + clib_warning ("svm msg q returned"); + continue; + } + e = svm_msg_q_msg_data (em->our_event_queue, &msg); + if (e->event_type != SESSION_IO_EVT_RX) + handle_mq_event (e); + svm_msg_q_free_msg (em->our_event_queue, &msg); + } + + for (i = 0; i < em->n_clients; i++) + { + s = pool_elt_at_index (em->sessions, i); + client_disconnect (em, s); + } + + /* + * Stats and detach + */ + deltat = clib_time_now (&em->clib_time) - start_time; + fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds\n", + em->tx_total, em->tx_total / (1ULL << 20), + em->tx_total / (1ULL << 30), deltat); + fformat (stdout, "%.4f Gbit/second\n", (em->tx_total * 8.0) / deltat / 1e9); + + application_detach (em); +} + +static void +vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp) +{ + echo_main_t *em = &echo_main; + + if (mp->retval) + { + clib_warning ("bind failed: %U", format_api_error, + clib_net_to_host_u32 (mp->retval)); + em->state = STATE_FAILED; + return; + } + + em->state = STATE_READY; +} + +static void +vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp) +{ + echo_main_t *em = &echo_main; + + if (mp->retval != 0) + clib_warning ("returned %d", ntohl (mp->retval)); + + em->state = STATE_START; +} + +u8 * +format_ip4_address (u8 * s, va_list * args) +{ + u8 *a = va_arg (*args, u8 *); + return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); +} + +u8 * +format_ip6_address (u8 * s, va_list * args) +{ + ip6_address_t *a = va_arg (*args, ip6_address_t *); + u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon; + + i_max_n_zero = ARRAY_LEN (a->as_u16); + max_n_zeros = 0; + i_first_zero = i_max_n_zero; + n_zeros = 0; + for (i = 0; i < ARRAY_LEN (a->as_u16); i++) + { + u32 is_zero = a->as_u16[i] == 0; + if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16)) + { + i_first_zero = i; + n_zeros = 0; + } + n_zeros += is_zero; + if ((!is_zero && n_zeros > max_n_zeros) + || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros)) + { + i_max_n_zero = i_first_zero; + max_n_zeros = n_zeros; + i_first_zero = ARRAY_LEN (a->as_u16); + n_zeros = 0; + } + } + + last_double_colon = 0; + for (i = 0; i < ARRAY_LEN (a->as_u16); i++) + { + if (i == i_max_n_zero && max_n_zeros > 1) + { + s = format (s, "::"); + i += max_n_zeros - 1; + last_double_colon = 1; + } + else + { + s = format (s, "%s%x", + (last_double_colon || i == 0) ? "" : ":", + clib_net_to_host_u16 (a->as_u16[i])); + last_double_colon = 0; + } + } + + return s; +} + +/* Format an IP46 address. */ +u8 * +format_ip46_address (u8 * s, va_list * args) +{ + ip46_address_t *ip46 = va_arg (*args, ip46_address_t *); + ip46_type_t type = va_arg (*args, ip46_type_t); + int is_ip4 = 1; + + switch (type) + { + case IP46_TYPE_ANY: + is_ip4 = ip46_address_is_ip4 (ip46); + break; + case IP46_TYPE_IP4: + is_ip4 = 1; + break; + case IP46_TYPE_IP6: + is_ip4 = 0; + break; + } + + return is_ip4 ? + format (s, "%U", format_ip4_address, &ip46->ip4) : + format (s, "%U", format_ip6_address, &ip46->ip6); +} + +static void +server_handle_rx (echo_main_t * em, session_event_t * e) +{ + int n_read, max_dequeue, n_sent; + u32 offset, to_dequeue; + echo_session_t *s; + + s = pool_elt_at_index (em->sessions, e->session_index); + + /* Clear event only once. Otherwise, if we do it in the loop by calling + * app_recv_stream, we may end up with a lot of unhandled rx events on the + * message queue */ + svm_fifo_unset_event (s->rx_fifo); + + max_dequeue = svm_fifo_max_dequeue_cons (s->rx_fifo); + if (PREDICT_FALSE (!max_dequeue)) + return; + + do + { + /* The options here are to limit ourselves to max_dequeue or read + * even the data that was enqueued while we were dequeueing and which + * now has an rx event in the mq. Either of the two work. */ + to_dequeue = clib_min (max_dequeue, vec_len (em->rx_buf)); + n_read = app_recv_stream_raw (s->rx_fifo, em->rx_buf, to_dequeue, + 0 /* clear evt */ , 0 /* peek */ ); + if (n_read > 0) + { + max_dequeue -= n_read; + s->bytes_received += n_read; + } + else + break; + + /* Reflect if a non-drop session */ + if (!em->no_return && n_read > 0) + { + offset = 0; + do + { + n_sent = app_send_stream ((app_session_t *) s, + &em->rx_buf[offset], + n_read, SVM_Q_WAIT); + if (n_sent > 0) + { + n_read -= n_sent; + offset += n_sent; + } + } + while ((n_sent <= 0 || n_read > 0) && !em->time_to_stop); + } + } + while (max_dequeue > 0 && !em->time_to_stop); +} + +static void +server_handle_mq (echo_main_t * em) +{ + svm_msg_q_msg_t msg; + session_event_t *e; + + while (1) + { + svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_WAIT, 0); + e = svm_msg_q_msg_data (em->our_event_queue, &msg); + switch (e->event_type) + { + case SESSION_IO_EVT_RX: + server_handle_rx (em, e); + break; + default: + handle_mq_event (e); + break; + } + if (PREDICT_FALSE (em->time_to_stop == 1)) + break; + if (PREDICT_FALSE (em->time_to_print_stats == 1)) + { + em->time_to_print_stats = 0; + fformat (stdout, "%d connections\n", pool_elts (em->sessions)); + } + svm_msg_q_free_msg (em->our_event_queue, &msg); + } +} + +void +server_send_listen (echo_main_t * em) +{ + vl_api_bind_uri_t *bmp; + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_BIND_URI); + bmp->client_index = em->my_client_index; + bmp->context = ntohl (0xfeedface); + memcpy (bmp->uri, em->uri, vec_len (em->uri)); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); +} + +int +server_listen (echo_main_t * em) +{ + server_send_listen (em); + if (wait_for_state_change (em, STATE_READY)) + { + clib_warning ("timeout waiting for STATE_READY"); + return -1; + } + return 0; +} + +void +server_send_unbind (echo_main_t * em) +{ + vl_api_unbind_uri_t *ump; + + ump = vl_msg_api_alloc (sizeof (*ump)); + clib_memset (ump, 0, sizeof (*ump)); + + ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI); + ump->client_index = em->my_client_index; + memcpy (ump->uri, em->uri, vec_len (em->uri)); + vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & ump); +} + +int +server_unbind (echo_main_t * em) +{ + server_send_unbind (em); + if (wait_for_state_change (em, STATE_START)) + { + clib_warning ("timeout waiting for STATE_START"); + return -1; + } + return 0; +} + +void +server_run (echo_main_t * em) +{ + echo_session_t *session; + int i; + + /* $$$$ hack preallocation */ + for (i = 0; i < 200000; i++) + { + pool_get (em->sessions, session); + clib_memset (session, 0, sizeof (*session)); + } + for (i = 0; i < 200000; i++) + pool_put_index (em->sessions, i); + + if (application_attach (em)) + return; + + /* Bind to uri */ + if (server_listen (em)) + return; + + /* Enter handle event loop */ + server_handle_mq (em); + + /* Cleanup */ + server_send_unbind (em); + + application_detach (em); + + fformat (stdout, "Test complete...\n"); +} + +static void +vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t * + mp) +{ + echo_main_t *em = &echo_main; + uword *p; + + if (mp->retval) + { + clib_warning ("vpp complained about disconnect: %d", + ntohl (mp->retval)); + return; + } + + em->state = STATE_START; + + p = hash_get (em->session_index_by_vpp_handles, mp->handle); + if (p) + { + hash_unset (em->session_index_by_vpp_handles, mp->handle); + } + else + { + clib_warning ("couldn't find session key %llx", mp->handle); + } +} + +static void + vl_api_application_tls_cert_add_reply_t_handler + (vl_api_application_tls_cert_add_reply_t * mp) +{ + if (mp->retval) + clib_warning ("failed to add tls cert"); +} + +static void + vl_api_application_tls_key_add_reply_t_handler + (vl_api_application_tls_key_add_reply_t * mp) +{ + if (mp->retval) + clib_warning ("failed to add tls key"); +} + +#define foreach_tcp_echo_msg \ +_(BIND_URI_REPLY, bind_uri_reply) \ +_(UNBIND_URI_REPLY, unbind_uri_reply) \ +_(DISCONNECT_SESSION_REPLY, disconnect_session_reply) \ +_(APPLICATION_ATTACH_REPLY, application_attach_reply) \ +_(APPLICATION_DETACH_REPLY, application_detach_reply) \ +_(MAP_ANOTHER_SEGMENT, map_another_segment) \ +_(APPLICATION_TLS_CERT_ADD_REPLY, application_tls_cert_add_reply) \ +_(APPLICATION_TLS_KEY_ADD_REPLY, application_tls_key_add_reply) \ + +void +tcp_echo_api_hookup (echo_main_t * em) +{ +#define _(N,n) \ + vl_msg_api_set_handlers(VL_API_##N, #n, \ + vl_api_##n##_t_handler, \ + vl_noop_handler, \ + vl_api_##n##_t_endian, \ + vl_api_##n##_t_print, \ + sizeof(vl_api_##n##_t), 1); + foreach_tcp_echo_msg; +#undef _ +} + +int +main (int argc, char **argv) +{ + int i_am_server = 1, test_return_packets = 0; + echo_main_t *em = &echo_main; + fifo_segment_main_t *sm = &em->segment_main; + unformat_input_t _argv, *a = &_argv; + u8 *chroot_prefix; + u8 *uri = 0; + u8 *bind_uri = (u8 *) "tcp://0.0.0.0/1234"; + u8 *connect_uri = (u8 *) "tcp://6.0.1.1/1234"; + u64 bytes_to_send = 64 << 10, mbytes; + char *app_name; + u32 tmp; + + clib_mem_init_thread_safe (0, 256 << 20); + + clib_memset (em, 0, sizeof (*em)); + em->session_index_by_vpp_handles = hash_create (0, sizeof (uword)); + em->my_pid = getpid (); + em->configured_segment_size = 1 << 20; + em->socket_name = 0; + em->use_sock_api = 1; + em->fifo_size = 64 << 10; + em->n_clients = 1; + + clib_time_init (&em->clib_time); + init_error_string_table (em); + fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20); + unformat_init_command_line (a, argv); + + while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT) + { + if (unformat (a, "chroot prefix %s", &chroot_prefix)) + { + vl_set_memory_root_path ((char *) chroot_prefix); + } + else if (unformat (a, "uri %s", &uri)) + ; + else if (unformat (a, "segment-size %dM", &tmp)) + em->configured_segment_size = tmp << 20; + else if (unformat (a, "segment-size %dG", &tmp)) + em->configured_segment_size = tmp << 30; + else if (unformat (a, "server")) + i_am_server = 1; + else if (unformat (a, "client")) + i_am_server = 0; + else if (unformat (a, "no-return")) + em->no_return = 1; + else if (unformat (a, "test")) + test_return_packets = 1; + else if (unformat (a, "mbytes %lld", &mbytes)) + { + bytes_to_send = mbytes << 20; + } + else if (unformat (a, "gbytes %lld", &mbytes)) + { + bytes_to_send = mbytes << 30; + } + else if (unformat (a, "socket-name %s", &em->socket_name)) + ; + else if (unformat (a, "use-svm-api")) + em->use_sock_api = 0; + else if (unformat (a, "fifo-size %d", &tmp)) + em->fifo_size = tmp << 10; + else if (unformat (a, "nclients %d", &em->n_clients)) + ; + else + { + fformat (stderr, "%s: usage [master|slave]\n", argv[0]); + exit (1); + } + } + + if (!em->socket_name) + em->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0); + + if (uri) + { + em->uri = format (0, "%s%c", uri, 0); + em->connect_uri = format (0, "%s%c", uri, 0); + } + else + { + em->uri = format (0, "%s%c", bind_uri, 0); + em->connect_uri = format (0, "%s%c", connect_uri, 0); + } + + em->i_am_master = i_am_server; + em->test_return_packets = test_return_packets; + em->bytes_to_send = bytes_to_send; + em->time_to_stop = 0; + vec_validate (em->rx_buf, 4 << 20); + vec_validate (em->client_thread_handles, em->n_clients - 1); + vec_validate (em->thread_args, em->n_clients - 1); + + setup_signal_handlers (); + tcp_echo_api_hookup (em); + + app_name = i_am_server ? "tcp_echo_server" : "tcp_echo_client"; + if (connect_to_vpp (app_name) < 0) + { + svm_region_exit (); + fformat (stderr, "Couldn't connect to vpe, exiting...\n"); + exit (1); + } + + if (i_am_server == 0) + clients_run (em); + else + server_run (em); + + /* Make sure detach finishes */ + wait_for_state_change (em, STATE_DETACHED); + + disconnect_from_vpp (em); + exit (0); +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/src/plugins/hs_apps/sapi/udp_echo.c b/src/plugins/hs_apps/sapi/udp_echo.c new file mode 100644 index 00000000000..c9992befe98 --- /dev/null +++ b/src/plugins/hs_apps/sapi/udp_echo.c @@ -0,0 +1,1256 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define vl_typedefs /* define message structures */ +#include +#undef vl_typedefs + +/* declare message handlers for each api */ + +#define vl_endianfun /* define message structures */ +#include +#undef vl_endianfun + +/* instantiate all the print functions we know about */ +#define vl_print(handle, ...) +#define vl_printfun +#include +#undef vl_printfun + +typedef enum +{ + STATE_START, + STATE_ATTACHED, + STATE_BOUND, + STATE_READY, + STATE_FAILED, + STATE_DISCONNECTING, + STATE_DETACHED +} connection_state_t; + +typedef struct +{ + /* vpe input queue */ + svm_queue_t *vl_input_queue; + + /* API client handle */ + u32 my_client_index; + + /* The URI we're playing with */ + u8 *listen_uri; + + /* URI for connect */ + u8 *connect_uri; + + /* Session pool */ + app_session_t *sessions; + + /* Hash table for disconnect processing */ + uword *session_index_by_vpp_handles; + + /* fifo segment */ + fifo_segment_t *seg; + + /* intermediate rx buffer */ + u8 *rx_buf; + + u32 fifo_size; + int i_am_server; + u8 is_connected; + + /* Our event queue */ + svm_msg_q_t *our_event_queue; + svm_msg_q_t *ct_event_queue; + + /* $$$ single thread only for the moment */ + svm_msg_q_t *vpp_event_queue; + + /* $$$$ hack: cut-through session index */ + volatile u32 cut_through_session_index; + volatile u32 connected_session; + + /* unique segment name counter */ + u32 unique_segment_index; + + pid_t my_pid; + + /* pthread handle */ + pthread_t cut_through_thread_handle; + + /* For deadman timers */ + clib_time_t clib_time; + + /* State of the connection, shared between msg RX thread and main thread */ + volatile connection_state_t state; + + volatile int time_to_stop; + volatile int time_to_print_stats; + + u32 configured_segment_size; + + /* VNET_API_ERROR_FOO -> "Foo" hash table */ + uword *error_string_by_error_number; + + fifo_segment_main_t segment_main; + + u8 *connect_test_data; + + uword *segments_table; + u8 do_echo; + u8 have_return; + u64 total_to_send; + u64 bytes_to_send; + u64 bytes_sent; +} udp_echo_main_t; + +udp_echo_main_t udp_echo_main; + +static void +stop_signal (int signum) +{ + udp_echo_main_t *um = &udp_echo_main; + + um->time_to_stop = 1; +} + +static void +stats_signal (int signum) +{ + udp_echo_main_t *um = &udp_echo_main; + um->time_to_print_stats = 1; +} + +static clib_error_t * +setup_signal_handlers (void) +{ + signal (SIGINT, stats_signal); + signal (SIGQUIT, stop_signal); + signal (SIGTERM, stop_signal); + + return 0; +} + +uword +unformat_ip4_address (unformat_input_t * input, va_list * args) +{ + u8 *result = va_arg (*args, u8 *); + unsigned a[4]; + + if (!unformat (input, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3])) + return 0; + + if (a[0] >= 256 || a[1] >= 256 || a[2] >= 256 || a[3] >= 256) + return 0; + + result[0] = a[0]; + result[1] = a[1]; + result[2] = a[2]; + result[3] = a[3]; + + return 1; +} + +uword +unformat_ip6_address (unformat_input_t * input, va_list * args) +{ + ip6_address_t *result = va_arg (*args, ip6_address_t *); + u16 hex_quads[8]; + uword hex_quad, n_hex_quads, hex_digit, n_hex_digits; + uword c, n_colon, double_colon_index; + + n_hex_quads = hex_quad = n_hex_digits = n_colon = 0; + double_colon_index = ARRAY_LEN (hex_quads); + while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT) + { + hex_digit = 16; + if (c >= '0' && c <= '9') + hex_digit = c - '0'; + else if (c >= 'a' && c <= 'f') + hex_digit = c + 10 - 'a'; + else if (c >= 'A' && c <= 'F') + hex_digit = c + 10 - 'A'; + else if (c == ':' && n_colon < 2) + n_colon++; + else + { + unformat_put_input (input); + break; + } + + /* Too many hex quads. */ + if (n_hex_quads >= ARRAY_LEN (hex_quads)) + return 0; + + if (hex_digit < 16) + { + hex_quad = (hex_quad << 4) | hex_digit; + + /* Hex quad must fit in 16 bits. */ + if (n_hex_digits >= 4) + return 0; + + n_colon = 0; + n_hex_digits++; + } + + /* Save position of :: */ + if (n_colon == 2) + { + /* More than one :: ? */ + if (double_colon_index < ARRAY_LEN (hex_quads)) + return 0; + double_colon_index = n_hex_quads; + } + + if (n_colon > 0 && n_hex_digits > 0) + { + hex_quads[n_hex_quads++] = hex_quad; + hex_quad = 0; + n_hex_digits = 0; + } + } + + if (n_hex_digits > 0) + hex_quads[n_hex_quads++] = hex_quad; + + { + word i; + + /* Expand :: to appropriate number of zero hex quads. */ + if (double_colon_index < ARRAY_LEN (hex_quads)) + { + word n_zero = ARRAY_LEN (hex_quads) - n_hex_quads; + + for (i = n_hex_quads - 1; i >= (signed) double_colon_index; i--) + hex_quads[n_zero + i] = hex_quads[i]; + + for (i = 0; i < n_zero; i++) + hex_quads[double_colon_index + i] = 0; + + n_hex_quads = ARRAY_LEN (hex_quads); + } + + /* Too few hex quads given. */ + if (n_hex_quads < ARRAY_LEN (hex_quads)) + return 0; + + for (i = 0; i < ARRAY_LEN (hex_quads); i++) + result->as_u16[i] = clib_host_to_net_u16 (hex_quads[i]); + + return 1; + } +} + +uword +unformat_uri (unformat_input_t * input, va_list * args) +{ + session_endpoint_cfg_t *sep = va_arg (*args, session_endpoint_cfg_t *); + u32 port; + char *tmp; + + if (unformat (input, "%s://%U/%d", &tmp, unformat_ip4_address, &sep->ip.ip4, + &port)) + { + sep->port = clib_host_to_net_u16 (port); + sep->is_ip4 = 1; + return 1; + } + else if (unformat (input, "%s://%U/%d", &tmp, unformat_ip6_address, + &sep->ip.ip6, &port)) + { + sep->port = clib_host_to_net_u16 (port); + sep->is_ip4 = 0; + return 1; + } + return 0; +} + +static void +application_send_attach (udp_echo_main_t * utm) +{ + vl_api_application_attach_t *bmp; + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH); + bmp->client_index = utm->my_client_index; + bmp->context = ntohl (0xfeedface); + bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ADD_SEGMENT; + bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE; + bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE; + bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 2; + bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = utm->fifo_size; + bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = utm->fifo_size; + bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20; + bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20; + bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 16768; + vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp); +} + +void +application_detach (udp_echo_main_t * utm) +{ + vl_api_application_detach_t *bmp; + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH); + bmp->client_index = utm->my_client_index; + bmp->context = ntohl (0xfeedface); + vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp); +} + +static void +vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t * + mp) +{ + fifo_segment_create_args_t _a = { 0 }, *a = &_a; + udp_echo_main_t *utm = &udp_echo_main; + fifo_segment_main_t *sm = &utm->segment_main; + int rv; + + if (mp->retval) + { + clib_warning ("attach failed: %d", mp->retval); + utm->state = STATE_FAILED; + return; + } + + if (mp->segment_name_length == 0) + { + clib_warning ("segment_name_length zero"); + return; + } + + a->segment_name = (char *) mp->segment_name; + a->segment_size = mp->segment_size; + + ASSERT (mp->app_event_queue_address); + + /* Attach to the segment vpp created */ + rv = fifo_segment_attach (sm, a); + if (rv) + { + clib_warning ("svm_fifo_segment_attach ('%s') failed", + mp->segment_name); + return; + } + + utm->our_event_queue = uword_to_pointer (mp->app_event_queue_address, + svm_msg_q_t *); + utm->state = STATE_ATTACHED; +} + +static void +vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t * + mp) +{ + if (mp->retval) + clib_warning ("detach returned with err: %d", mp->retval); + udp_echo_main.state = STATE_DETACHED; +} + +u8 * +format_api_error (u8 * s, va_list * args) +{ + udp_echo_main_t *utm = va_arg (*args, udp_echo_main_t *); + i32 error = va_arg (*args, u32); + uword *p; + + p = hash_get (utm->error_string_by_error_number, -error); + + if (p) + s = format (s, "%s", p[0]); + else + s = format (s, "%d", error); + return s; +} + +int +wait_for_state_change (udp_echo_main_t * utm, connection_state_t state) +{ +#if CLIB_DEBUG > 0 +#define TIMEOUT 600.0 +#else +#define TIMEOUT 600.0 +#endif + + f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT; + + while (clib_time_now (&utm->clib_time) < timeout) + { + if (utm->state == state) + return 0; + if (utm->state == STATE_FAILED) + return -1; + } + return -1; +} + +u64 server_bytes_received, server_bytes_sent; + +__clib_unused static void * +cut_through_thread_fn (void *arg) +{ + app_session_t *s; + svm_fifo_t *rx_fifo; + svm_fifo_t *tx_fifo; + u8 *my_copy_buffer = 0; + udp_echo_main_t *utm = &udp_echo_main; + i32 actual_transfer; + int rv, do_dequeue = 0; + u32 buffer_offset; + + while (utm->cut_through_session_index == ~0) + ; + + s = pool_elt_at_index (utm->sessions, utm->cut_through_session_index); + + rx_fifo = s->rx_fifo; + tx_fifo = s->tx_fifo; + + vec_validate (my_copy_buffer, 64 * 1024 - 1); + + while (1) + { + do + { + /* We read from the tx fifo and write to the rx fifo */ + if (utm->have_return || do_dequeue) + actual_transfer = svm_fifo_dequeue (rx_fifo, + vec_len (my_copy_buffer), + my_copy_buffer); + else + { + /* We don't do anything with the data, drop it */ + actual_transfer = svm_fifo_max_dequeue_cons (rx_fifo); + svm_fifo_dequeue_drop (rx_fifo, actual_transfer); + } + } + while (actual_transfer <= 0); + + server_bytes_received += actual_transfer; + + if (utm->have_return) + { + buffer_offset = 0; + while (actual_transfer > 0) + { + rv = svm_fifo_enqueue (tx_fifo, actual_transfer, + my_copy_buffer + buffer_offset); + if (rv > 0) + { + actual_transfer -= rv; + buffer_offset += rv; + server_bytes_sent += rv; + } + + } + } + if (PREDICT_FALSE (utm->time_to_stop)) + break; + } + + pthread_exit (0); +} + +static void +session_accepted_handler (session_accepted_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + udp_echo_main_t *utm = &udp_echo_main; + session_accepted_reply_msg_t *rmp; + svm_fifo_t *rx_fifo, *tx_fifo; + app_session_t *session; + static f64 start_time; + u32 session_index; + int rv = 0; + + if (start_time == 0.0) + start_time = clib_time_now (&utm->clib_time); + + utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address, + svm_msg_q_t *); + rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); + tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); + + pool_get (utm->sessions, session); + clib_memset (session, 0, sizeof (*session)); + session_index = session - utm->sessions; + session->session_index = session_index; + + rx_fifo->client_session_index = session_index; + tx_fifo->client_session_index = session_index; + session->rx_fifo = rx_fifo; + session->tx_fifo = tx_fifo; + clib_memcpy_fast (&session->transport.rmt_ip, &mp->rmt.ip, + sizeof (ip46_address_t)); + session->transport.is_ip4 = mp->rmt.is_ip4; + session->transport.rmt_port = mp->rmt.port; + + hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index); + if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0) + { + f64 now = clib_time_now (&utm->clib_time); + fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n", + pool_elts (utm->sessions), now - start_time, + (f64) pool_elts (utm->sessions) / (now - start_time)); + } + + app_alloc_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt, + SESSION_CTRL_EVT_ACCEPTED_REPLY); + rmp = (session_accepted_reply_msg_t *) app_evt->evt->data; + rmp->handle = mp->handle; + rmp->context = mp->context; + rmp->retval = rv; + app_send_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt); + + CLIB_MEMORY_BARRIER (); + utm->state = STATE_READY; +} + +static void +session_disconnected_handler (session_disconnected_msg_t * mp) +{ + app_session_evt_t _app_evt, *app_evt = &_app_evt; + udp_echo_main_t *utm = &udp_echo_main; + session_disconnected_reply_msg_t *rmp; + app_session_t *session; + uword *p; + int rv = 0; + + p = hash_get (utm->session_index_by_vpp_handles, mp->handle); + + if (p) + { + session = pool_elt_at_index (utm->sessions, p[0]); + hash_unset (utm->session_index_by_vpp_handles, mp->handle); + clib_warning ("disconnecting %u", session->session_index); + pool_put (utm->sessions, session); + } + else + { + clib_warning ("couldn't find session key %llx", mp->handle); + return; + } + + app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, + SESSION_CTRL_EVT_DISCONNECTED_REPLY); + rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data; + rmp->retval = rv; + rmp->handle = mp->handle; + rmp->context = mp->context; + app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); +} + +static void +session_connected_handler (session_connected_msg_t * mp) +{ + udp_echo_main_t *utm = &udp_echo_main; + unformat_input_t _input, *input = &_input; + session_endpoint_cfg_t _sep, *sep = &_sep; + app_session_t *session; + + ASSERT (utm->i_am_server == 0); + + if (mp->retval) + { + clib_warning ("failed connect"); + return; + } + + ASSERT (mp->server_rx_fifo && mp->server_tx_fifo); + + pool_get (utm->sessions, session); + session->session_index = session - utm->sessions; + session->rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); + session->tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); + + /* Cut-through case */ + if (mp->ct_rx_fifo) + { + clib_warning ("cut-through session"); + session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, + svm_msg_q_t *); + utm->cut_through_session_index = session->session_index; + session->is_dgram = 0; + sleep (1); + session->rx_fifo->client_session_index = session->session_index; + session->tx_fifo->client_session_index = session->session_index; + /* TODO use ct fifos */ + } + else + { + utm->connected_session = session->session_index; + utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address, + svm_msg_q_t *); + + session->rx_fifo->client_session_index = session->session_index; + session->tx_fifo->client_session_index = session->session_index; + clib_memcpy_fast (&session->transport.lcl_ip, &mp->lcl.ip, + sizeof (ip46_address_t)); + session->transport.is_ip4 = mp->lcl.is_ip4; + session->transport.lcl_port = mp->lcl.port; + + unformat_init_vector (input, utm->connect_uri); + if (!unformat (input, "%U", unformat_uri, sep)) + { + clib_warning ("can't figure out remote ip and port"); + utm->state = STATE_FAILED; + unformat_free (input); + return; + } + unformat_free (input); + clib_memcpy_fast (&session->transport.rmt_ip, &sep->ip, + sizeof (ip46_address_t)); + session->transport.rmt_port = sep->port; + session->is_dgram = !utm->is_connected; + } + utm->state = STATE_READY; +} + +static void +session_bound_handler (session_bound_msg_t * mp) +{ + udp_echo_main_t *utm = &udp_echo_main; + svm_fifo_t *rx_fifo, *tx_fifo; + app_session_t *session; + u32 session_index; + + if (mp->retval) + { + clib_warning ("bind failed: %d", mp->retval); + utm->state = STATE_FAILED; + return; + } + + rx_fifo = uword_to_pointer (mp->rx_fifo, svm_fifo_t *); + tx_fifo = uword_to_pointer (mp->tx_fifo, svm_fifo_t *); + + pool_get (utm->sessions, session); + clib_memset (session, 0, sizeof (*session)); + session_index = session - utm->sessions; + + rx_fifo->client_session_index = session_index; + tx_fifo->client_session_index = session_index; + session->rx_fifo = rx_fifo; + session->tx_fifo = tx_fifo; + clib_memcpy_fast (&session->transport.lcl_ip, mp->lcl_ip, + sizeof (ip46_address_t)); + session->transport.is_ip4 = mp->lcl_is_ip4; + session->transport.lcl_port = mp->lcl_port; + session->vpp_evt_q = uword_to_pointer (mp->vpp_evt_q, svm_msg_q_t *); + + utm->state = utm->is_connected ? STATE_BOUND : STATE_READY; +} + +static void +handle_mq_event (session_event_t * e) +{ + switch (e->event_type) + { + case SESSION_CTRL_EVT_BOUND: + session_bound_handler ((session_bound_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_ACCEPTED: + session_accepted_handler ((session_accepted_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_CONNECTED: + session_connected_handler ((session_connected_msg_t *) e->data); + break; + case SESSION_CTRL_EVT_DISCONNECTED: + session_disconnected_handler ((session_disconnected_msg_t *) e->data); + break; + default: + clib_warning ("unhandled %u", e->event_type); + } +} + +static void +udp_client_send_connect (udp_echo_main_t * utm) +{ + vl_api_connect_uri_t *cmp; + cmp = vl_msg_api_alloc (sizeof (*cmp)); + clib_memset (cmp, 0, sizeof (*cmp)); + + cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI); + cmp->client_index = utm->my_client_index; + cmp->context = ntohl (0xfeedface); + memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri)); + vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp); +} + +static void +send_test_chunk (udp_echo_main_t * utm, app_session_t * s, u32 bytes) +{ + u64 test_buf_len, bytes_this_chunk, test_buf_offset; + + u8 *test_data = utm->connect_test_data; + u32 enq_space; + int written; + + test_buf_len = vec_len (test_data); + test_buf_offset = utm->bytes_sent % test_buf_len; + bytes_this_chunk = clib_min (test_buf_len - test_buf_offset, + utm->bytes_to_send); + enq_space = svm_fifo_max_enqueue_prod (s->tx_fifo); + bytes_this_chunk = clib_min (bytes_this_chunk, enq_space); + + written = app_send (s, test_data + test_buf_offset, bytes_this_chunk, + SVM_Q_WAIT); + if (written > 0) + { + utm->bytes_to_send -= written; + utm->bytes_sent += written; + } +} + +static void +recv_test_chunk (udp_echo_main_t * utm, app_session_t * s) +{ + app_recv (s, utm->rx_buf, vec_len (utm->rx_buf)); +} + +void +client_send_data (udp_echo_main_t * utm, u32 session_index) +{ + f64 start_time, end_time, delta; + app_session_t *session; + char *transfer_type; + u8 *test_data; + int i; + + vec_validate_aligned (utm->connect_test_data, 1024 * 1024 - 1, + CLIB_CACHE_LINE_BYTES); + for (i = 0; i < vec_len (utm->connect_test_data); i++) + utm->connect_test_data[i] = i & 0xff; + + test_data = utm->connect_test_data; + session = pool_elt_at_index (utm->sessions, session_index); + ASSERT (vec_len (test_data) > 0); + + utm->total_to_send = utm->bytes_to_send; + vec_validate (utm->rx_buf, vec_len (test_data) - 1); + start_time = clib_time_now (&utm->clib_time); + while (!utm->time_to_stop && utm->bytes_to_send) + { + send_test_chunk (utm, session, 0); + if (utm->have_return) + recv_test_chunk (utm, session); + if (utm->time_to_stop) + break; + } + + if (utm->have_return) + { + f64 timeout = clib_time_now (&utm->clib_time) + 5; + while (clib_time_now (&utm->clib_time) < timeout) + recv_test_chunk (utm, session); + } + + end_time = clib_time_now (&utm->clib_time); + delta = end_time - start_time; + transfer_type = utm->have_return ? "full-duplex" : "half-duplex"; + clib_warning ("%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds", + utm->total_to_send, utm->total_to_send / (1ULL << 20), + utm->total_to_send / (1ULL << 30), delta); + clib_warning ("%.2f bytes/second %s", ((f64) utm->total_to_send) / (delta), + transfer_type); + clib_warning ("%.4f gbit/second %s", + (((f64) utm->total_to_send * 8.0) / delta / 1e9), + transfer_type); +} + +static int +application_attach (udp_echo_main_t * utm) +{ + application_send_attach (utm); + if (wait_for_state_change (utm, STATE_ATTACHED)) + { + clib_warning ("timeout waiting for STATE_ATTACHED"); + return -1; + } + return 0; +} + +static void +client_test (udp_echo_main_t * utm) +{ + f64 start_time, timeout = 100.0; + svm_msg_q_msg_t msg; + session_event_t *e; + + if (application_attach (utm)) + return; + + udp_client_send_connect (utm); + + start_time = clib_time_now (&utm->clib_time); + while (pool_elts (utm->sessions) != 1 && utm->state != STATE_FAILED) + { + svm_msg_q_sub (utm->our_event_queue, &msg, SVM_Q_WAIT, 0); + e = svm_msg_q_msg_data (utm->our_event_queue, &msg); + handle_mq_event (e); + svm_msg_q_free_msg (utm->our_event_queue, &msg); + + if (clib_time_now (&utm->clib_time) - start_time >= timeout) + break; + } + + if (utm->cut_through_session_index != ~0) + client_send_data (utm, utm->cut_through_session_index); + else + client_send_data (utm, utm->connected_session); + + application_detach (utm); + wait_for_state_change (utm, STATE_DETACHED); +} + +static void +vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp) +{ + fifo_segment_create_args_t _a, *a = &_a; + udp_echo_main_t *utm = &udp_echo_main; + fifo_segment_main_t *sm = &utm->segment_main; + fifo_segment_t *seg; + int rv; + + clib_memset (a, 0, sizeof (*a)); + a->segment_name = (char *) mp->segment_name; + a->segment_size = mp->segment_size; + /* Attach to the segment vpp created */ + rv = fifo_segment_attach (sm, a); + if (rv) + { + clib_warning ("svm_fifo_segment_attach ('%s') failed", + mp->segment_name); + return; + } + seg = fifo_segment_get_segment (sm, a->new_segment_indices[0]); + clib_warning ("Mapped new segment '%s' size %d", seg->ssvm.name, + seg->ssvm.ssvm_size); + hash_set (utm->segments_table, clib_net_to_host_u64 (mp->segment_handle), + a->new_segment_indices[0]); +} + +static void +vl_api_unmap_segment_t_handler (vl_api_unmap_segment_t * mp) +{ + udp_echo_main_t *utm = &udp_echo_main; + fifo_segment_main_t *sm = &utm->segment_main; + fifo_segment_t *seg; + uword *seg_indexp; + u64 segment_handle; + + segment_handle = clib_net_to_host_u64 (mp->segment_handle); + seg_indexp = hash_get (utm->segments_table, segment_handle); + if (!seg_indexp) + { + clib_warning ("segment not mapped: %s", segment_handle); + return; + } + hash_unset (utm->segments_table, segment_handle); + seg = fifo_segment_get_segment (sm, (u32) seg_indexp[0]); + fifo_segment_delete (sm, seg); + clib_warning ("Unmapped segment '%s'", segment_handle); +} + +static void +vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp) +{ + udp_echo_main_t *utm = &udp_echo_main; + + if (mp->retval != 0) + clib_warning ("returned %d", ntohl (mp->retval)); + + utm->state = STATE_START; +} + +static void + vl_api_app_cut_through_registration_add_t_handler + (vl_api_app_cut_through_registration_add_t * mp) +{ + +} + +#define foreach_tcp_echo_msg \ +_(UNBIND_URI_REPLY, unbind_uri_reply) \ +_(MAP_ANOTHER_SEGMENT, map_another_segment) \ +_(UNMAP_SEGMENT, unmap_segment) \ +_(APPLICATION_ATTACH_REPLY, application_attach_reply) \ +_(APPLICATION_DETACH_REPLY, application_detach_reply) \ +_(APP_CUT_THROUGH_REGISTRATION_ADD, app_cut_through_registration_add) \ + +void +tcp_echo_api_hookup (udp_echo_main_t * utm) +{ +#define _(N,n) \ + vl_msg_api_set_handlers(VL_API_##N, #n, \ + vl_api_##n##_t_handler, \ + vl_noop_handler, \ + vl_api_##n##_t_endian, \ + vl_api_##n##_t_print, \ + sizeof(vl_api_##n##_t), 1); + foreach_tcp_echo_msg; +#undef _ + +} + +int +connect_to_vpp (char *name) +{ + udp_echo_main_t *utm = &udp_echo_main; + api_main_t *am = &api_main; + + if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0) + return -1; + + utm->vl_input_queue = am->shmem_hdr->vl_input_queue; + utm->my_client_index = am->my_client_index; + + return 0; +} + +void +vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...) +{ + clib_warning ("BUG"); +} + +static void +init_error_string_table (udp_echo_main_t * utm) +{ + utm->error_string_by_error_number = hash_create (0, sizeof (uword)); + +#define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s); + foreach_vnet_api_error; +#undef _ + + hash_set (utm->error_string_by_error_number, 99, "Misc"); +} + +void +server_handle_fifo_event_rx (udp_echo_main_t * utm, u32 session_index) +{ + svm_fifo_t *rx_fifo, *tx_fifo; + int n_read; + app_session_t *session; + int rv; + u32 max_dequeue, offset, max_transfer, rx_buf_len; + + session = pool_elt_at_index (utm->sessions, session_index); + rx_buf_len = vec_len (utm->rx_buf); + rx_fifo = session->rx_fifo; + tx_fifo = session->tx_fifo; + + + max_dequeue = svm_fifo_max_dequeue_cons (rx_fifo); + /* Allow enqueuing of a new event */ + svm_fifo_unset_event (rx_fifo); + + if (PREDICT_FALSE (!max_dequeue)) + return; + + /* Read the max_dequeue */ + do + { + max_transfer = clib_min (rx_buf_len, max_dequeue); + if (session->is_dgram) + n_read = app_recv_dgram_raw (rx_fifo, utm->rx_buf, max_transfer, + &session->transport, 0, 0); + else + n_read = app_recv_stream_raw (rx_fifo, utm->rx_buf, max_transfer, 0, + 0); + + if (n_read > 0) + max_dequeue -= n_read; + + /* Reflect if a non-drop session */ + if (utm->have_return && n_read > 0) + { + offset = 0; + do + { + rv = app_send (session, &utm->rx_buf[offset], n_read, + SVM_Q_WAIT); + if (rv > 0) + { + n_read -= rv; + offset += rv; + } + } + while ((rv <= 0 || n_read > 0) && !utm->time_to_stop); + + /* If event wasn't set, add one */ + if (svm_fifo_set_event (tx_fifo)) + app_send_io_evt_to_vpp (session->vpp_evt_q, + tx_fifo->master_session_index, + SESSION_IO_EVT_TX, SVM_Q_WAIT); + } + } + while ((n_read < 0 || max_dequeue > 0) && !utm->time_to_stop); +} + +static void +server_handle_event_queue (udp_echo_main_t * utm) +{ + session_event_t *e; + svm_msg_q_msg_t msg; + svm_msg_q_t *mq = utm->our_event_queue; + + while (utm->state != STATE_READY) + sleep (5); + + while (1) + { + if (svm_msg_q_sub (mq, &msg, SVM_Q_WAIT, 0)) + { + clib_warning ("svm msg q returned"); + continue; + } + e = svm_msg_q_msg_data (mq, &msg); + switch (e->event_type) + { + case SESSION_IO_EVT_RX: + server_handle_fifo_event_rx (utm, e->session_index); + break; + + default: + handle_mq_event (e); + break; + } + svm_msg_q_free_msg (mq, &msg); + if (PREDICT_FALSE (utm->time_to_stop == 1)) + return; + if (PREDICT_FALSE (utm->time_to_print_stats == 1)) + { + utm->time_to_print_stats = 0; + fformat (stdout, "%d connections\n", pool_elts (utm->sessions)); + } + } +} + +static void +server_unbind (udp_echo_main_t * utm) +{ + vl_api_unbind_uri_t *ump; + + ump = vl_msg_api_alloc (sizeof (*ump)); + clib_memset (ump, 0, sizeof (*ump)); + + ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI); + ump->client_index = utm->my_client_index; + memcpy (ump->uri, utm->listen_uri, vec_len (utm->listen_uri)); + vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump); +} + +static void +server_bind (udp_echo_main_t * utm) +{ + vl_api_bind_uri_t *bmp; + + bmp = vl_msg_api_alloc (sizeof (*bmp)); + clib_memset (bmp, 0, sizeof (*bmp)); + + bmp->_vl_msg_id = ntohs (VL_API_BIND_URI); + bmp->client_index = utm->my_client_index; + bmp->context = ntohl (0xfeedface); + memcpy (bmp->uri, utm->listen_uri, vec_len (utm->listen_uri)); + vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp); +} + +void +udp_server_test (udp_echo_main_t * utm) +{ + u8 wait_for_state = utm->is_connected ? STATE_BOUND : STATE_READY; + application_send_attach (utm); + + /* Bind to uri */ + server_bind (utm); + + if (wait_for_state_change (utm, wait_for_state)) + { + clib_warning ("timeout waiting for state change"); + return; + } + + server_handle_event_queue (utm); + + /* Cleanup */ + server_unbind (utm); + + if (wait_for_state_change (utm, STATE_START)) + { + clib_warning ("timeout waiting for STATE_START"); + return; + } + + application_detach (utm); + + fformat (stdout, "Test complete...\n"); +} + +int +main (int argc, char **argv) +{ + udp_echo_main_t *utm = &udp_echo_main; + fifo_segment_main_t *sm = &utm->segment_main; + u8 *uri = (u8 *) "udp://6.0.1.1/1234"; + unformat_input_t _argv, *a = &_argv; + int i_am_server = 1; + app_session_t *session; + u8 *chroot_prefix; + char *app_name; + u32 tmp; + int i; + + clib_mem_init_thread_safe (0, 256 << 20); + + fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20); + + vec_validate (utm->rx_buf, 128 << 10); + utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword)); + utm->my_pid = getpid (); + utm->configured_segment_size = 1 << 20; + utm->have_return = 1; + utm->bytes_to_send = 1024; + utm->fifo_size = 128 << 10; + utm->cut_through_session_index = ~0; + clib_time_init (&utm->clib_time); + + init_error_string_table (utm); + unformat_init_command_line (a, argv); + + while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT) + { + if (unformat (a, "chroot prefix %s", &chroot_prefix)) + { + vl_set_memory_root_path ((char *) chroot_prefix); + } + else if (unformat (a, "uri %s", &uri)) + ; + else if (unformat (a, "segment-size %dM", &tmp)) + utm->configured_segment_size = tmp << 20; + else if (unformat (a, "segment-size %dG", &tmp)) + utm->configured_segment_size = tmp << 30; + else if (unformat (a, "server")) + i_am_server = 1; + else if (unformat (a, "client")) + i_am_server = 0; + else if (unformat (a, "no-return")) + utm->have_return = 0; + else if (unformat (a, "mbytes %d", &tmp)) + utm->bytes_to_send = (u64) tmp << 20; + else if (unformat (a, "fifo-size %d", &tmp)) + utm->fifo_size = tmp << 10; + else + { + fformat (stderr, "%s: usage [server|client]\n"); + exit (1); + } + } + + utm->i_am_server = i_am_server; + + setup_signal_handlers (); + tcp_echo_api_hookup (utm); + + if (i_am_server) + { + utm->listen_uri = format (0, "%s%c", uri, 0); + utm->is_connected = (utm->listen_uri[4] == 'c'); + app_name = "udp_echo_server"; + } + else + { + app_name = "udp_echo_client"; + utm->connect_uri = format (0, "%s%c", uri, 0); + utm->is_connected = (utm->connect_uri[4] == 'c'); + } + if (connect_to_vpp (app_name) < 0) + { + svm_region_exit (); + fformat (stderr, "Couldn't connect to vpe, exiting...\n"); + exit (1); + } + + if (i_am_server == 0) + { + client_test (utm); + goto done; + } + + /* $$$$ hack preallocation */ + for (i = 0; i < 200000; i++) + { + pool_get (utm->sessions, session); + clib_memset (session, 0, sizeof (*session)); + } + for (i = 0; i < 200000; i++) + pool_put_index (utm->sessions, i); + + udp_server_test (utm); + +done: + vl_client_disconnect_from_vlib (); + exit (0); +} + +#undef vl_api_version +#define vl_api_version(n,v) static u32 vpe_api_version = v; +#include +#undef vl_api_version + +void +vl_client_add_api_signatures (vl_api_memclnt_create_t * mp) +{ + /* + * Send the main API signature in slot 0. This bit of code must + * match the checks in ../vpe/api/api.c: vl_msg_api_version_check(). + */ + mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version); +} + +u32 +vl (void *p) +{ + return vec_len (p); +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/src/plugins/hs_apps/tcp_echo.c b/src/plugins/hs_apps/tcp_echo.c deleted file mode 100644 index 6c3ce928490..00000000000 --- a/src/plugins/hs_apps/tcp_echo.c +++ /dev/null @@ -1,1414 +0,0 @@ -/* - * Copyright (c) 2016 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include -#include - -#include -#include - -#define vl_typedefs /* define message structures */ -#include -#undef vl_typedefs - -/* declare message handlers for each api */ - -#define vl_endianfun /* define message structures */ -#include -#undef vl_endianfun - -/* instantiate all the print functions we know about */ -#define vl_print(handle, ...) -#define vl_printfun -#include -#undef vl_printfun - -#define TCP_ECHO_DBG 0 -#define DBG(_fmt,_args...) \ - if (TCP_ECHO_DBG) \ - clib_warning (_fmt, _args) - -typedef struct -{ - CLIB_CACHE_LINE_ALIGN_MARK (cacheline0); -#define _(type, name) type name; - foreach_app_session_field -#undef _ - u64 vpp_session_handle; - u64 bytes_sent; - u64 bytes_to_send; - volatile u64 bytes_received; - volatile u64 bytes_to_receive; - f64 start; -} echo_session_t; - -typedef enum -{ - STATE_START, - STATE_ATTACHED, - STATE_LISTEN, - STATE_READY, - STATE_DISCONNECTING, - STATE_FAILED, - STATE_DETACHED -} connection_state_t; - -typedef struct -{ - /* vpe input queue */ - svm_queue_t *vl_input_queue; - - /* API client handle */ - u32 my_client_index; - - /* The URI we're playing with */ - u8 *uri; - - /* Session pool */ - echo_session_t *sessions; - - /* Hash table for disconnect processing */ - uword *session_index_by_vpp_handles; - - /* intermediate rx buffer */ - u8 *rx_buf; - - /* URI for slave's connect */ - u8 *connect_uri; - - u32 connected_session_index; - - int i_am_master; - - /* drop all packets */ - int no_return; - - /* Our event queue */ - svm_msg_q_t *our_event_queue; - - u8 *socket_name; - - pid_t my_pid; - - /* For deadman timers */ - clib_time_t clib_time; - - /* State of the connection, shared between msg RX thread and main thread */ - volatile connection_state_t state; - - /* Signal variables */ - volatile int time_to_stop; - volatile int time_to_print_stats; - - u32 configured_segment_size; - - /* VNET_API_ERROR_FOO -> "Foo" hash table */ - uword *error_string_by_error_number; - - u8 *connect_test_data; - pthread_t *client_thread_handles; - u32 *thread_args; - u32 client_bytes_received; - u8 test_return_packets; - u64 bytes_to_send; - u32 fifo_size; - - u32 n_clients; - u64 tx_total; - u64 rx_total; - - volatile u32 n_clients_connected; - volatile u32 n_active_clients; - - - /** Flag that decides if socket, instead of svm, api is used to connect to - * vpp. If sock api is used, shm binary api is subsequently bootstrapped - * and all other messages are exchanged using shm IPC. */ - u8 use_sock_api; - - fifo_segment_main_t segment_main; -} echo_main_t; - -echo_main_t echo_main; - -#if CLIB_DEBUG > 0 -#define NITER 10000 -#else -#define NITER 4000000 -#endif - -static u8 * -format_api_error (u8 * s, va_list * args) -{ - echo_main_t *em = &echo_main; - i32 error = va_arg (*args, u32); - uword *p; - - p = hash_get (em->error_string_by_error_number, -error); - - if (p) - s = format (s, "%s", p[0]); - else - s = format (s, "%d", error); - return s; -} - -static void -init_error_string_table (echo_main_t * em) -{ - em->error_string_by_error_number = hash_create (0, sizeof (uword)); - -#define _(n,v,s) hash_set (em->error_string_by_error_number, -v, s); - foreach_vnet_api_error; -#undef _ - - hash_set (em->error_string_by_error_number, 99, "Misc"); -} - -static void handle_mq_event (session_event_t * e); - -static int -wait_for_state_change (echo_main_t * em, connection_state_t state) -{ - svm_msg_q_msg_t msg; - session_event_t *e; - f64 timeout; - -#if CLIB_DEBUG > 0 -#define TIMEOUT 600.0 -#else -#define TIMEOUT 600.0 -#endif - - timeout = clib_time_now (&em->clib_time) + TIMEOUT; - - while (clib_time_now (&em->clib_time) < timeout) - { - if (em->state == state) - return 0; - if (em->state == STATE_FAILED) - return -1; - if (em->time_to_stop == 1) - return 0; - if (!em->our_event_queue || em->state < STATE_ATTACHED) - continue; - - if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_NOWAIT, 0)) - continue; - e = svm_msg_q_msg_data (em->our_event_queue, &msg); - handle_mq_event (e); - svm_msg_q_free_msg (em->our_event_queue, &msg); - } - clib_warning ("timeout waiting for state %d", state); - return -1; -} - -void -application_send_attach (echo_main_t * em) -{ - vl_api_application_attach_t *bmp; - vl_api_application_tls_cert_add_t *cert_mp; - vl_api_application_tls_key_add_t *key_mp; - - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH); - bmp->client_index = em->my_client_index; - bmp->context = ntohl (0xfeedface); - bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ACCEPT_REDIRECT; - bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_ADD_SEGMENT; - bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 16; - bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = em->fifo_size; - bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = em->fifo_size; - bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20; - bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20; - bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 256; - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); - - cert_mp = vl_msg_api_alloc (sizeof (*cert_mp) + test_srv_crt_rsa_len); - clib_memset (cert_mp, 0, sizeof (*cert_mp)); - cert_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_CERT_ADD); - cert_mp->client_index = em->my_client_index; - cert_mp->context = ntohl (0xfeedface); - cert_mp->cert_len = clib_host_to_net_u16 (test_srv_crt_rsa_len); - clib_memcpy_fast (cert_mp->cert, test_srv_crt_rsa, test_srv_crt_rsa_len); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cert_mp); - - key_mp = vl_msg_api_alloc (sizeof (*key_mp) + test_srv_key_rsa_len); - clib_memset (key_mp, 0, sizeof (*key_mp) + test_srv_key_rsa_len); - key_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_KEY_ADD); - key_mp->client_index = em->my_client_index; - key_mp->context = ntohl (0xfeedface); - key_mp->key_len = clib_host_to_net_u16 (test_srv_key_rsa_len); - clib_memcpy_fast (key_mp->key, test_srv_key_rsa, test_srv_key_rsa_len); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & key_mp); -} - -static int -application_attach (echo_main_t * em) -{ - application_send_attach (em); - if (wait_for_state_change (em, STATE_ATTACHED)) - { - clib_warning ("timeout waiting for STATE_ATTACHED"); - return -1; - } - return 0; -} - -void -application_detach (echo_main_t * em) -{ - vl_api_application_detach_t *bmp; - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH); - bmp->client_index = em->my_client_index; - bmp->context = ntohl (0xfeedface); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); - - DBG ("%s", "Sent detach"); -} - -static int -ssvm_segment_attach (char *name, ssvm_segment_type_t type, int fd) -{ - fifo_segment_create_args_t _a, *a = &_a; - fifo_segment_main_t *sm = &echo_main.segment_main; - int rv; - - clib_memset (a, 0, sizeof (*a)); - a->segment_name = (char *) name; - a->segment_type = type; - - if (type == SSVM_SEGMENT_MEMFD) - a->memfd_fd = fd; - - if ((rv = fifo_segment_attach (sm, a))) - { - clib_warning ("svm_fifo_segment_attach ('%s') failed", name); - return rv; - } - - vec_reset_length (a->new_segment_indices); - return 0; -} - -static void -vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t * - mp) -{ - echo_main_t *em = &echo_main; - int *fds = 0; - u32 n_fds = 0; - - if (mp->retval) - { - clib_warning ("attach failed: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - goto failed; - } - - if (mp->segment_name_length == 0) - { - clib_warning ("segment_name_length zero"); - goto failed; - } - - ASSERT (mp->app_event_queue_address); - em->our_event_queue = uword_to_pointer (mp->app_event_queue_address, - svm_msg_q_t *); - - if (mp->n_fds) - { - vec_validate (fds, mp->n_fds); - vl_socket_client_recv_fd_msg (fds, mp->n_fds, 5); - - if (mp->fd_flags & SESSION_FD_F_VPP_MQ_SEGMENT) - if (ssvm_segment_attach (0, SSVM_SEGMENT_MEMFD, fds[n_fds++])) - goto failed; - - if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT) - if (ssvm_segment_attach ((char *) mp->segment_name, - SSVM_SEGMENT_MEMFD, fds[n_fds++])) - goto failed; - - if (mp->fd_flags & SESSION_FD_F_MQ_EVENTFD) - svm_msg_q_set_consumer_eventfd (em->our_event_queue, fds[n_fds++]); - - vec_free (fds); - } - else - { - if (ssvm_segment_attach ((char *) mp->segment_name, SSVM_SEGMENT_SHM, - -1)) - goto failed; - } - - em->state = STATE_ATTACHED; - return; -failed: - em->state = STATE_FAILED; - return; -} - -static void -vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t * - mp) -{ - if (mp->retval) - clib_warning ("detach returned with err: %d", mp->retval); - echo_main.state = STATE_DETACHED; -} - -static void -stop_signal (int signum) -{ - echo_main_t *um = &echo_main; - - um->time_to_stop = 1; -} - -static void -stats_signal (int signum) -{ - echo_main_t *um = &echo_main; - - um->time_to_print_stats = 1; -} - -static clib_error_t * -setup_signal_handlers (void) -{ - signal (SIGINT, stats_signal); - signal (SIGQUIT, stop_signal); - signal (SIGTERM, stop_signal); - - return 0; -} - -void -vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...) -{ - clib_warning ("BUG"); -} - -int -connect_to_vpp (char *name) -{ - echo_main_t *em = &echo_main; - api_main_t *am = &api_main; - - if (em->use_sock_api) - { - if (vl_socket_client_connect ((char *) em->socket_name, name, - 0 /* default rx, tx buffer */ )) - { - clib_warning ("socket connect failed"); - return -1; - } - - if (vl_socket_client_init_shm (0, 1 /* want_pthread */ )) - { - clib_warning ("init shm api failed"); - return -1; - } - } - else - { - if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0) - { - clib_warning ("shmem connect failed"); - return -1; - } - } - em->vl_input_queue = am->shmem_hdr->vl_input_queue; - em->my_client_index = am->my_client_index; - return 0; -} - -void -disconnect_from_vpp (echo_main_t * em) -{ - if (em->use_sock_api) - vl_socket_client_disconnect (); - else - vl_client_disconnect_from_vlib (); -} - -static void -vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp) -{ - fifo_segment_main_t *sm = &echo_main.segment_main; - fifo_segment_create_args_t _a, *a = &_a; - int rv; - - clib_memset (a, 0, sizeof (*a)); - a->segment_name = (char *) mp->segment_name; - a->segment_size = mp->segment_size; - /* Attach to the segment vpp created */ - rv = fifo_segment_attach (sm, a); - if (rv) - { - clib_warning ("svm_fifo_segment_attach ('%s') failed", - mp->segment_name); - return; - } - clib_warning ("Mapped new segment '%s' size %d", mp->segment_name, - mp->segment_size); -} - -static void -session_print_stats (echo_main_t * em, echo_session_t * session) -{ - f64 deltat; - u64 bytes; - - deltat = clib_time_now (&em->clib_time) - session->start; - bytes = em->i_am_master ? session->bytes_received : em->bytes_to_send; - fformat (stdout, "Finished in %.6f\n", deltat); - fformat (stdout, "%.4f Gbit/second\n", (bytes * 8.0) / deltat / 1e9); -} - -static void -test_recv_bytes (echo_session_t * s, u8 * rx_buf, u32 n_read) -{ - int i; - for (i = 0; i < n_read; i++) - { - if (rx_buf[i] != ((s->bytes_received + i) & 0xff)) - { - clib_warning ("error at byte %lld, 0x%x not 0x%x", - s->bytes_received + i, rx_buf[i], - ((s->bytes_received + i) & 0xff)); - } - } -} - -static void -recv_data_chunk (echo_main_t * em, echo_session_t * s, u8 * rx_buf) -{ - int n_to_read, n_read; - - n_to_read = svm_fifo_max_dequeue_cons (s->rx_fifo); - if (!n_to_read) - return; - - do - { - n_read = app_recv_stream ((app_session_t *) s, rx_buf, - vec_len (rx_buf)); - - if (n_read > 0) - { - if (em->test_return_packets) - test_recv_bytes (s, rx_buf, n_read); - - n_to_read -= n_read; - - s->bytes_received += n_read; - s->bytes_to_receive -= n_read; - } - else - break; - } - while (n_to_read > 0); -} - -static void -send_data_chunk (echo_main_t * em, echo_session_t * s) -{ - u64 test_buf_len, bytes_this_chunk, test_buf_offset; - u8 *test_data = em->connect_test_data; - int n_sent; - - test_buf_len = vec_len (test_data); - test_buf_offset = s->bytes_sent % test_buf_len; - bytes_this_chunk = clib_min (test_buf_len - test_buf_offset, - s->bytes_to_send); - - n_sent = app_send_stream ((app_session_t *) s, test_data + test_buf_offset, - bytes_this_chunk, 0); - - if (n_sent > 0) - { - s->bytes_to_send -= n_sent; - s->bytes_sent += n_sent; - } -} - -/* - * Rx/Tx polling thread per connection - */ -static void * -client_thread_fn (void *arg) -{ - echo_main_t *em = &echo_main; - static u8 *rx_buf = 0; - u32 session_index = *(u32 *) arg; - echo_session_t *s; - - vec_validate (rx_buf, 1 << 20); - - while (!em->time_to_stop && em->state != STATE_READY) - ; - - s = pool_elt_at_index (em->sessions, session_index); - while (!em->time_to_stop) - { - send_data_chunk (em, s); - recv_data_chunk (em, s, rx_buf); - if (!s->bytes_to_send && !s->bytes_to_receive) - break; - } - - DBG ("session %d done", session_index); - em->tx_total += s->bytes_sent; - em->rx_total += s->bytes_received; - em->n_active_clients--; - - pthread_exit (0); -} - -void -client_send_connect (echo_main_t * em) -{ - vl_api_connect_uri_t *cmp; - cmp = vl_msg_api_alloc (sizeof (*cmp)); - clib_memset (cmp, 0, sizeof (*cmp)); - - cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI); - cmp->client_index = em->my_client_index; - cmp->context = ntohl (0xfeedface); - memcpy (cmp->uri, em->connect_uri, vec_len (em->connect_uri)); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cmp); -} - -void -client_send_disconnect (echo_main_t * em, echo_session_t * s) -{ - vl_api_disconnect_session_t *dmp; - dmp = vl_msg_api_alloc (sizeof (*dmp)); - clib_memset (dmp, 0, sizeof (*dmp)); - dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION); - dmp->client_index = em->my_client_index; - dmp->handle = s->vpp_session_handle; - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & dmp); -} - -int -client_disconnect (echo_main_t * em, echo_session_t * s) -{ - client_send_disconnect (em, s); - pool_put (em->sessions, s); - clib_memset (s, 0xfe, sizeof (*s)); - return 0; -} - -static void -session_bound_handler (session_bound_msg_t * mp) -{ - echo_main_t *em = &echo_main; - - if (mp->retval) - { - clib_warning ("bind failed: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - em->state = STATE_FAILED; - return; - } - - clib_warning ("listening on %U:%u", format_ip46_address, mp->lcl_ip, - mp->lcl_is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6, mp->lcl_port); - em->state = STATE_READY; -} - -static void -session_accepted_handler (session_accepted_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - session_accepted_reply_msg_t *rmp; - svm_fifo_t *rx_fifo, *tx_fifo; - echo_main_t *em = &echo_main; - echo_session_t *session; - static f64 start_time; - u32 session_index; - u8 *ip_str; - - if (start_time == 0.0) - start_time = clib_time_now (&em->clib_time); - - ip_str = format (0, "%U", format_ip46_address, &mp->rmt.ip, mp->rmt.is_ip4); - clib_warning ("Accepted session from: %s:%d", ip_str, - clib_net_to_host_u16 (mp->rmt.port)); - - /* Allocate local session and set it up */ - pool_get (em->sessions, session); - session_index = session - em->sessions; - - rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); - rx_fifo->client_session_index = session_index; - tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); - tx_fifo->client_session_index = session_index; - - session->rx_fifo = rx_fifo; - session->tx_fifo = tx_fifo; - session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, - svm_msg_q_t *); - - /* Add it to lookup table */ - hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); - - em->state = STATE_READY; - - /* Stats printing */ - if (pool_elts (em->sessions) && (pool_elts (em->sessions) % 20000) == 0) - { - f64 now = clib_time_now (&em->clib_time); - fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n", - pool_elts (em->sessions), now - start_time, - (f64) pool_elts (em->sessions) / (now - start_time)); - } - - /* - * Send accept reply to vpp - */ - app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, - SESSION_CTRL_EVT_ACCEPTED_REPLY); - rmp = (session_accepted_reply_msg_t *) app_evt->evt->data; - rmp->handle = mp->handle; - rmp->context = mp->context; - app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); - - session->bytes_received = 0; - session->start = clib_time_now (&em->clib_time); -} - -static void -session_connected_handler (session_connected_msg_t * mp) -{ - echo_main_t *em = &echo_main; - echo_session_t *session; - u32 session_index; - svm_fifo_t *rx_fifo, *tx_fifo; - int rv; - - if (mp->retval) - { - clib_warning ("connection failed with code: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - em->state = STATE_FAILED; - return; - } - - /* - * Setup session - */ - - pool_get (em->sessions, session); - clib_memset (session, 0, sizeof (*session)); - session_index = session - em->sessions; - - rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); - rx_fifo->client_session_index = session_index; - tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); - tx_fifo->client_session_index = session_index; - - session->rx_fifo = rx_fifo; - session->tx_fifo = tx_fifo; - session->vpp_session_handle = mp->handle; - session->start = clib_time_now (&em->clib_time); - session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, - svm_msg_q_t *); - - hash_set (em->session_index_by_vpp_handles, mp->handle, session_index); - - /* - * Start RX thread - */ - em->thread_args[em->n_clients_connected] = session_index; - rv = pthread_create (&em->client_thread_handles[em->n_clients_connected], - NULL /*attr */ , client_thread_fn, - (void *) &em->thread_args[em->n_clients_connected]); - if (rv) - { - clib_warning ("pthread_create returned %d", rv); - return; - } - - em->n_clients_connected += 1; - clib_warning ("session %u (0x%llx) connected with local ip %U port %d", - session_index, mp->handle, format_ip46_address, &mp->lcl.ip, - mp->lcl.is_ip4, clib_net_to_host_u16 (mp->lcl.port)); -} - -static void -session_disconnected_handler (session_disconnected_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - session_disconnected_reply_msg_t *rmp; - echo_main_t *em = &echo_main; - echo_session_t *session = 0; - uword *p; - int rv = 0; - - p = hash_get (em->session_index_by_vpp_handles, mp->handle); - if (!p) - { - clib_warning ("couldn't find session key %llx", mp->handle); - return; - } - - session = pool_elt_at_index (em->sessions, p[0]); - hash_unset (em->session_index_by_vpp_handles, mp->handle); - pool_put (em->sessions, session); - - app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, - SESSION_CTRL_EVT_DISCONNECTED_REPLY); - rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data; - rmp->retval = rv; - rmp->handle = mp->handle; - rmp->context = mp->context; - app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); - - session_print_stats (em, session); -} - -static void -session_reset_handler (session_reset_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - echo_main_t *em = &echo_main; - session_reset_reply_msg_t *rmp; - echo_session_t *session = 0; - uword *p; - int rv = 0; - - p = hash_get (em->session_index_by_vpp_handles, mp->handle); - - if (p) - { - session = pool_elt_at_index (em->sessions, p[0]); - clib_warning ("got reset"); - /* Cleanup later */ - em->time_to_stop = 1; - } - else - { - clib_warning ("couldn't find session key %llx", mp->handle); - return; - } - - app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, - SESSION_CTRL_EVT_RESET_REPLY); - rmp = (session_reset_reply_msg_t *) app_evt->evt->data; - rmp->retval = rv; - rmp->handle = mp->handle; - app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); -} - -static void -handle_mq_event (session_event_t * e) -{ - switch (e->event_type) - { - case SESSION_CTRL_EVT_BOUND: - session_bound_handler ((session_bound_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_ACCEPTED: - session_accepted_handler ((session_accepted_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_CONNECTED: - session_connected_handler ((session_connected_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_DISCONNECTED: - session_disconnected_handler ((session_disconnected_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_RESET: - session_reset_handler ((session_reset_msg_t *) e->data); - break; - default: - clib_warning ("unhandled %u", e->event_type); - } -} - -static void -clients_run (echo_main_t * em) -{ - f64 start_time, deltat, timeout = 100.0; - svm_msg_q_msg_t msg; - session_event_t *e; - echo_session_t *s; - int i; - - /* Init test data */ - vec_validate (em->connect_test_data, 1024 * 1024 - 1); - for (i = 0; i < vec_len (em->connect_test_data); i++) - em->connect_test_data[i] = i & 0xff; - - /* - * Attach and connect the clients - */ - if (application_attach (em)) - return; - - for (i = 0; i < em->n_clients; i++) - client_send_connect (em); - - start_time = clib_time_now (&em->clib_time); - while (em->n_clients_connected < em->n_clients - && (clib_time_now (&em->clib_time) - start_time < timeout) - && em->state != STATE_FAILED) - - { - svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_WAIT, 0); - e = svm_msg_q_msg_data (em->our_event_queue, &msg); - handle_mq_event (e); - svm_msg_q_free_msg (em->our_event_queue, &msg); - } - - if (em->n_clients_connected != em->n_clients) - { - clib_warning ("failed to initialize all connections"); - return; - } - - /* - * Initialize connections - */ - for (i = 0; i < em->n_clients; i++) - { - s = pool_elt_at_index (em->sessions, i); - s->bytes_to_send = em->bytes_to_send; - if (!em->no_return) - s->bytes_to_receive = em->bytes_to_send; - } - em->n_active_clients = em->n_clients_connected; - - /* - * Wait for client threads to send the data - */ - start_time = clib_time_now (&em->clib_time); - em->state = STATE_READY; - while (em->n_active_clients) - if (!svm_msg_q_is_empty (em->our_event_queue)) - { - if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_WAIT, 0)) - { - clib_warning ("svm msg q returned"); - continue; - } - e = svm_msg_q_msg_data (em->our_event_queue, &msg); - if (e->event_type != SESSION_IO_EVT_RX) - handle_mq_event (e); - svm_msg_q_free_msg (em->our_event_queue, &msg); - } - - for (i = 0; i < em->n_clients; i++) - { - s = pool_elt_at_index (em->sessions, i); - client_disconnect (em, s); - } - - /* - * Stats and detach - */ - deltat = clib_time_now (&em->clib_time) - start_time; - fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds\n", - em->tx_total, em->tx_total / (1ULL << 20), - em->tx_total / (1ULL << 30), deltat); - fformat (stdout, "%.4f Gbit/second\n", (em->tx_total * 8.0) / deltat / 1e9); - - application_detach (em); -} - -static void -vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp) -{ - echo_main_t *em = &echo_main; - - if (mp->retval) - { - clib_warning ("bind failed: %U", format_api_error, - clib_net_to_host_u32 (mp->retval)); - em->state = STATE_FAILED; - return; - } - - em->state = STATE_READY; -} - -static void -vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp) -{ - echo_main_t *em = &echo_main; - - if (mp->retval != 0) - clib_warning ("returned %d", ntohl (mp->retval)); - - em->state = STATE_START; -} - -u8 * -format_ip4_address (u8 * s, va_list * args) -{ - u8 *a = va_arg (*args, u8 *); - return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); -} - -u8 * -format_ip6_address (u8 * s, va_list * args) -{ - ip6_address_t *a = va_arg (*args, ip6_address_t *); - u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon; - - i_max_n_zero = ARRAY_LEN (a->as_u16); - max_n_zeros = 0; - i_first_zero = i_max_n_zero; - n_zeros = 0; - for (i = 0; i < ARRAY_LEN (a->as_u16); i++) - { - u32 is_zero = a->as_u16[i] == 0; - if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16)) - { - i_first_zero = i; - n_zeros = 0; - } - n_zeros += is_zero; - if ((!is_zero && n_zeros > max_n_zeros) - || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros)) - { - i_max_n_zero = i_first_zero; - max_n_zeros = n_zeros; - i_first_zero = ARRAY_LEN (a->as_u16); - n_zeros = 0; - } - } - - last_double_colon = 0; - for (i = 0; i < ARRAY_LEN (a->as_u16); i++) - { - if (i == i_max_n_zero && max_n_zeros > 1) - { - s = format (s, "::"); - i += max_n_zeros - 1; - last_double_colon = 1; - } - else - { - s = format (s, "%s%x", - (last_double_colon || i == 0) ? "" : ":", - clib_net_to_host_u16 (a->as_u16[i])); - last_double_colon = 0; - } - } - - return s; -} - -/* Format an IP46 address. */ -u8 * -format_ip46_address (u8 * s, va_list * args) -{ - ip46_address_t *ip46 = va_arg (*args, ip46_address_t *); - ip46_type_t type = va_arg (*args, ip46_type_t); - int is_ip4 = 1; - - switch (type) - { - case IP46_TYPE_ANY: - is_ip4 = ip46_address_is_ip4 (ip46); - break; - case IP46_TYPE_IP4: - is_ip4 = 1; - break; - case IP46_TYPE_IP6: - is_ip4 = 0; - break; - } - - return is_ip4 ? - format (s, "%U", format_ip4_address, &ip46->ip4) : - format (s, "%U", format_ip6_address, &ip46->ip6); -} - -static void -server_handle_rx (echo_main_t * em, session_event_t * e) -{ - int n_read, max_dequeue, n_sent; - u32 offset, to_dequeue; - echo_session_t *s; - - s = pool_elt_at_index (em->sessions, e->session_index); - - /* Clear event only once. Otherwise, if we do it in the loop by calling - * app_recv_stream, we may end up with a lot of unhandled rx events on the - * message queue */ - svm_fifo_unset_event (s->rx_fifo); - - max_dequeue = svm_fifo_max_dequeue_cons (s->rx_fifo); - if (PREDICT_FALSE (!max_dequeue)) - return; - - do - { - /* The options here are to limit ourselves to max_dequeue or read - * even the data that was enqueued while we were dequeueing and which - * now has an rx event in the mq. Either of the two work. */ - to_dequeue = clib_min (max_dequeue, vec_len (em->rx_buf)); - n_read = app_recv_stream_raw (s->rx_fifo, em->rx_buf, to_dequeue, - 0 /* clear evt */ , 0 /* peek */ ); - if (n_read > 0) - { - max_dequeue -= n_read; - s->bytes_received += n_read; - } - else - break; - - /* Reflect if a non-drop session */ - if (!em->no_return && n_read > 0) - { - offset = 0; - do - { - n_sent = app_send_stream ((app_session_t *) s, - &em->rx_buf[offset], - n_read, SVM_Q_WAIT); - if (n_sent > 0) - { - n_read -= n_sent; - offset += n_sent; - } - } - while ((n_sent <= 0 || n_read > 0) && !em->time_to_stop); - } - } - while (max_dequeue > 0 && !em->time_to_stop); -} - -static void -server_handle_mq (echo_main_t * em) -{ - svm_msg_q_msg_t msg; - session_event_t *e; - - while (1) - { - svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_WAIT, 0); - e = svm_msg_q_msg_data (em->our_event_queue, &msg); - switch (e->event_type) - { - case SESSION_IO_EVT_RX: - server_handle_rx (em, e); - break; - default: - handle_mq_event (e); - break; - } - if (PREDICT_FALSE (em->time_to_stop == 1)) - break; - if (PREDICT_FALSE (em->time_to_print_stats == 1)) - { - em->time_to_print_stats = 0; - fformat (stdout, "%d connections\n", pool_elts (em->sessions)); - } - svm_msg_q_free_msg (em->our_event_queue, &msg); - } -} - -void -server_send_listen (echo_main_t * em) -{ - vl_api_bind_uri_t *bmp; - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_BIND_URI); - bmp->client_index = em->my_client_index; - bmp->context = ntohl (0xfeedface); - memcpy (bmp->uri, em->uri, vec_len (em->uri)); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp); -} - -int -server_listen (echo_main_t * em) -{ - server_send_listen (em); - if (wait_for_state_change (em, STATE_READY)) - { - clib_warning ("timeout waiting for STATE_READY"); - return -1; - } - return 0; -} - -void -server_send_unbind (echo_main_t * em) -{ - vl_api_unbind_uri_t *ump; - - ump = vl_msg_api_alloc (sizeof (*ump)); - clib_memset (ump, 0, sizeof (*ump)); - - ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI); - ump->client_index = em->my_client_index; - memcpy (ump->uri, em->uri, vec_len (em->uri)); - vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & ump); -} - -int -server_unbind (echo_main_t * em) -{ - server_send_unbind (em); - if (wait_for_state_change (em, STATE_START)) - { - clib_warning ("timeout waiting for STATE_START"); - return -1; - } - return 0; -} - -void -server_run (echo_main_t * em) -{ - echo_session_t *session; - int i; - - /* $$$$ hack preallocation */ - for (i = 0; i < 200000; i++) - { - pool_get (em->sessions, session); - clib_memset (session, 0, sizeof (*session)); - } - for (i = 0; i < 200000; i++) - pool_put_index (em->sessions, i); - - if (application_attach (em)) - return; - - /* Bind to uri */ - if (server_listen (em)) - return; - - /* Enter handle event loop */ - server_handle_mq (em); - - /* Cleanup */ - server_send_unbind (em); - - application_detach (em); - - fformat (stdout, "Test complete...\n"); -} - -static void -vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t * - mp) -{ - echo_main_t *em = &echo_main; - uword *p; - - if (mp->retval) - { - clib_warning ("vpp complained about disconnect: %d", - ntohl (mp->retval)); - return; - } - - em->state = STATE_START; - - p = hash_get (em->session_index_by_vpp_handles, mp->handle); - if (p) - { - hash_unset (em->session_index_by_vpp_handles, mp->handle); - } - else - { - clib_warning ("couldn't find session key %llx", mp->handle); - } -} - -static void - vl_api_application_tls_cert_add_reply_t_handler - (vl_api_application_tls_cert_add_reply_t * mp) -{ - if (mp->retval) - clib_warning ("failed to add tls cert"); -} - -static void - vl_api_application_tls_key_add_reply_t_handler - (vl_api_application_tls_key_add_reply_t * mp) -{ - if (mp->retval) - clib_warning ("failed to add tls key"); -} - -#define foreach_tcp_echo_msg \ -_(BIND_URI_REPLY, bind_uri_reply) \ -_(UNBIND_URI_REPLY, unbind_uri_reply) \ -_(DISCONNECT_SESSION_REPLY, disconnect_session_reply) \ -_(APPLICATION_ATTACH_REPLY, application_attach_reply) \ -_(APPLICATION_DETACH_REPLY, application_detach_reply) \ -_(MAP_ANOTHER_SEGMENT, map_another_segment) \ -_(APPLICATION_TLS_CERT_ADD_REPLY, application_tls_cert_add_reply) \ -_(APPLICATION_TLS_KEY_ADD_REPLY, application_tls_key_add_reply) \ - -void -tcp_echo_api_hookup (echo_main_t * em) -{ -#define _(N,n) \ - vl_msg_api_set_handlers(VL_API_##N, #n, \ - vl_api_##n##_t_handler, \ - vl_noop_handler, \ - vl_api_##n##_t_endian, \ - vl_api_##n##_t_print, \ - sizeof(vl_api_##n##_t), 1); - foreach_tcp_echo_msg; -#undef _ -} - -int -main (int argc, char **argv) -{ - int i_am_server = 1, test_return_packets = 0; - echo_main_t *em = &echo_main; - fifo_segment_main_t *sm = &em->segment_main; - unformat_input_t _argv, *a = &_argv; - u8 *chroot_prefix; - u8 *uri = 0; - u8 *bind_uri = (u8 *) "tcp://0.0.0.0/1234"; - u8 *connect_uri = (u8 *) "tcp://6.0.1.1/1234"; - u64 bytes_to_send = 64 << 10, mbytes; - char *app_name; - u32 tmp; - - clib_mem_init_thread_safe (0, 256 << 20); - - clib_memset (em, 0, sizeof (*em)); - em->session_index_by_vpp_handles = hash_create (0, sizeof (uword)); - em->my_pid = getpid (); - em->configured_segment_size = 1 << 20; - em->socket_name = 0; - em->use_sock_api = 1; - em->fifo_size = 64 << 10; - em->n_clients = 1; - - clib_time_init (&em->clib_time); - init_error_string_table (em); - fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20); - unformat_init_command_line (a, argv); - - while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT) - { - if (unformat (a, "chroot prefix %s", &chroot_prefix)) - { - vl_set_memory_root_path ((char *) chroot_prefix); - } - else if (unformat (a, "uri %s", &uri)) - ; - else if (unformat (a, "segment-size %dM", &tmp)) - em->configured_segment_size = tmp << 20; - else if (unformat (a, "segment-size %dG", &tmp)) - em->configured_segment_size = tmp << 30; - else if (unformat (a, "server")) - i_am_server = 1; - else if (unformat (a, "client")) - i_am_server = 0; - else if (unformat (a, "no-return")) - em->no_return = 1; - else if (unformat (a, "test")) - test_return_packets = 1; - else if (unformat (a, "mbytes %lld", &mbytes)) - { - bytes_to_send = mbytes << 20; - } - else if (unformat (a, "gbytes %lld", &mbytes)) - { - bytes_to_send = mbytes << 30; - } - else if (unformat (a, "socket-name %s", &em->socket_name)) - ; - else if (unformat (a, "use-svm-api")) - em->use_sock_api = 0; - else if (unformat (a, "fifo-size %d", &tmp)) - em->fifo_size = tmp << 10; - else if (unformat (a, "nclients %d", &em->n_clients)) - ; - else - { - fformat (stderr, "%s: usage [master|slave]\n", argv[0]); - exit (1); - } - } - - if (!em->socket_name) - em->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0); - - if (uri) - { - em->uri = format (0, "%s%c", uri, 0); - em->connect_uri = format (0, "%s%c", uri, 0); - } - else - { - em->uri = format (0, "%s%c", bind_uri, 0); - em->connect_uri = format (0, "%s%c", connect_uri, 0); - } - - em->i_am_master = i_am_server; - em->test_return_packets = test_return_packets; - em->bytes_to_send = bytes_to_send; - em->time_to_stop = 0; - vec_validate (em->rx_buf, 4 << 20); - vec_validate (em->client_thread_handles, em->n_clients - 1); - vec_validate (em->thread_args, em->n_clients - 1); - - setup_signal_handlers (); - tcp_echo_api_hookup (em); - - app_name = i_am_server ? "tcp_echo_server" : "tcp_echo_client"; - if (connect_to_vpp (app_name) < 0) - { - svm_region_exit (); - fformat (stderr, "Couldn't connect to vpe, exiting...\n"); - exit (1); - } - - if (i_am_server == 0) - clients_run (em); - else - server_run (em); - - /* Make sure detach finishes */ - wait_for_state_change (em, STATE_DETACHED); - - disconnect_from_vpp (em); - exit (0); -} - -/* - * fd.io coding-style-patch-verification: ON - * - * Local Variables: - * eval: (c-set-style "gnu") - * End: - */ diff --git a/src/plugins/hs_apps/udp_echo.c b/src/plugins/hs_apps/udp_echo.c deleted file mode 100644 index c9992befe98..00000000000 --- a/src/plugins/hs_apps/udp_echo.c +++ /dev/null @@ -1,1256 +0,0 @@ -/* - * Copyright (c) 2016 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define vl_typedefs /* define message structures */ -#include -#undef vl_typedefs - -/* declare message handlers for each api */ - -#define vl_endianfun /* define message structures */ -#include -#undef vl_endianfun - -/* instantiate all the print functions we know about */ -#define vl_print(handle, ...) -#define vl_printfun -#include -#undef vl_printfun - -typedef enum -{ - STATE_START, - STATE_ATTACHED, - STATE_BOUND, - STATE_READY, - STATE_FAILED, - STATE_DISCONNECTING, - STATE_DETACHED -} connection_state_t; - -typedef struct -{ - /* vpe input queue */ - svm_queue_t *vl_input_queue; - - /* API client handle */ - u32 my_client_index; - - /* The URI we're playing with */ - u8 *listen_uri; - - /* URI for connect */ - u8 *connect_uri; - - /* Session pool */ - app_session_t *sessions; - - /* Hash table for disconnect processing */ - uword *session_index_by_vpp_handles; - - /* fifo segment */ - fifo_segment_t *seg; - - /* intermediate rx buffer */ - u8 *rx_buf; - - u32 fifo_size; - int i_am_server; - u8 is_connected; - - /* Our event queue */ - svm_msg_q_t *our_event_queue; - svm_msg_q_t *ct_event_queue; - - /* $$$ single thread only for the moment */ - svm_msg_q_t *vpp_event_queue; - - /* $$$$ hack: cut-through session index */ - volatile u32 cut_through_session_index; - volatile u32 connected_session; - - /* unique segment name counter */ - u32 unique_segment_index; - - pid_t my_pid; - - /* pthread handle */ - pthread_t cut_through_thread_handle; - - /* For deadman timers */ - clib_time_t clib_time; - - /* State of the connection, shared between msg RX thread and main thread */ - volatile connection_state_t state; - - volatile int time_to_stop; - volatile int time_to_print_stats; - - u32 configured_segment_size; - - /* VNET_API_ERROR_FOO -> "Foo" hash table */ - uword *error_string_by_error_number; - - fifo_segment_main_t segment_main; - - u8 *connect_test_data; - - uword *segments_table; - u8 do_echo; - u8 have_return; - u64 total_to_send; - u64 bytes_to_send; - u64 bytes_sent; -} udp_echo_main_t; - -udp_echo_main_t udp_echo_main; - -static void -stop_signal (int signum) -{ - udp_echo_main_t *um = &udp_echo_main; - - um->time_to_stop = 1; -} - -static void -stats_signal (int signum) -{ - udp_echo_main_t *um = &udp_echo_main; - um->time_to_print_stats = 1; -} - -static clib_error_t * -setup_signal_handlers (void) -{ - signal (SIGINT, stats_signal); - signal (SIGQUIT, stop_signal); - signal (SIGTERM, stop_signal); - - return 0; -} - -uword -unformat_ip4_address (unformat_input_t * input, va_list * args) -{ - u8 *result = va_arg (*args, u8 *); - unsigned a[4]; - - if (!unformat (input, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3])) - return 0; - - if (a[0] >= 256 || a[1] >= 256 || a[2] >= 256 || a[3] >= 256) - return 0; - - result[0] = a[0]; - result[1] = a[1]; - result[2] = a[2]; - result[3] = a[3]; - - return 1; -} - -uword -unformat_ip6_address (unformat_input_t * input, va_list * args) -{ - ip6_address_t *result = va_arg (*args, ip6_address_t *); - u16 hex_quads[8]; - uword hex_quad, n_hex_quads, hex_digit, n_hex_digits; - uword c, n_colon, double_colon_index; - - n_hex_quads = hex_quad = n_hex_digits = n_colon = 0; - double_colon_index = ARRAY_LEN (hex_quads); - while ((c = unformat_get_input (input)) != UNFORMAT_END_OF_INPUT) - { - hex_digit = 16; - if (c >= '0' && c <= '9') - hex_digit = c - '0'; - else if (c >= 'a' && c <= 'f') - hex_digit = c + 10 - 'a'; - else if (c >= 'A' && c <= 'F') - hex_digit = c + 10 - 'A'; - else if (c == ':' && n_colon < 2) - n_colon++; - else - { - unformat_put_input (input); - break; - } - - /* Too many hex quads. */ - if (n_hex_quads >= ARRAY_LEN (hex_quads)) - return 0; - - if (hex_digit < 16) - { - hex_quad = (hex_quad << 4) | hex_digit; - - /* Hex quad must fit in 16 bits. */ - if (n_hex_digits >= 4) - return 0; - - n_colon = 0; - n_hex_digits++; - } - - /* Save position of :: */ - if (n_colon == 2) - { - /* More than one :: ? */ - if (double_colon_index < ARRAY_LEN (hex_quads)) - return 0; - double_colon_index = n_hex_quads; - } - - if (n_colon > 0 && n_hex_digits > 0) - { - hex_quads[n_hex_quads++] = hex_quad; - hex_quad = 0; - n_hex_digits = 0; - } - } - - if (n_hex_digits > 0) - hex_quads[n_hex_quads++] = hex_quad; - - { - word i; - - /* Expand :: to appropriate number of zero hex quads. */ - if (double_colon_index < ARRAY_LEN (hex_quads)) - { - word n_zero = ARRAY_LEN (hex_quads) - n_hex_quads; - - for (i = n_hex_quads - 1; i >= (signed) double_colon_index; i--) - hex_quads[n_zero + i] = hex_quads[i]; - - for (i = 0; i < n_zero; i++) - hex_quads[double_colon_index + i] = 0; - - n_hex_quads = ARRAY_LEN (hex_quads); - } - - /* Too few hex quads given. */ - if (n_hex_quads < ARRAY_LEN (hex_quads)) - return 0; - - for (i = 0; i < ARRAY_LEN (hex_quads); i++) - result->as_u16[i] = clib_host_to_net_u16 (hex_quads[i]); - - return 1; - } -} - -uword -unformat_uri (unformat_input_t * input, va_list * args) -{ - session_endpoint_cfg_t *sep = va_arg (*args, session_endpoint_cfg_t *); - u32 port; - char *tmp; - - if (unformat (input, "%s://%U/%d", &tmp, unformat_ip4_address, &sep->ip.ip4, - &port)) - { - sep->port = clib_host_to_net_u16 (port); - sep->is_ip4 = 1; - return 1; - } - else if (unformat (input, "%s://%U/%d", &tmp, unformat_ip6_address, - &sep->ip.ip6, &port)) - { - sep->port = clib_host_to_net_u16 (port); - sep->is_ip4 = 0; - return 1; - } - return 0; -} - -static void -application_send_attach (udp_echo_main_t * utm) -{ - vl_api_application_attach_t *bmp; - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH); - bmp->client_index = utm->my_client_index; - bmp->context = ntohl (0xfeedface); - bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ADD_SEGMENT; - bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE; - bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE; - bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 2; - bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = utm->fifo_size; - bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = utm->fifo_size; - bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20; - bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20; - bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 16768; - vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp); -} - -void -application_detach (udp_echo_main_t * utm) -{ - vl_api_application_detach_t *bmp; - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH); - bmp->client_index = utm->my_client_index; - bmp->context = ntohl (0xfeedface); - vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp); -} - -static void -vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t * - mp) -{ - fifo_segment_create_args_t _a = { 0 }, *a = &_a; - udp_echo_main_t *utm = &udp_echo_main; - fifo_segment_main_t *sm = &utm->segment_main; - int rv; - - if (mp->retval) - { - clib_warning ("attach failed: %d", mp->retval); - utm->state = STATE_FAILED; - return; - } - - if (mp->segment_name_length == 0) - { - clib_warning ("segment_name_length zero"); - return; - } - - a->segment_name = (char *) mp->segment_name; - a->segment_size = mp->segment_size; - - ASSERT (mp->app_event_queue_address); - - /* Attach to the segment vpp created */ - rv = fifo_segment_attach (sm, a); - if (rv) - { - clib_warning ("svm_fifo_segment_attach ('%s') failed", - mp->segment_name); - return; - } - - utm->our_event_queue = uword_to_pointer (mp->app_event_queue_address, - svm_msg_q_t *); - utm->state = STATE_ATTACHED; -} - -static void -vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t * - mp) -{ - if (mp->retval) - clib_warning ("detach returned with err: %d", mp->retval); - udp_echo_main.state = STATE_DETACHED; -} - -u8 * -format_api_error (u8 * s, va_list * args) -{ - udp_echo_main_t *utm = va_arg (*args, udp_echo_main_t *); - i32 error = va_arg (*args, u32); - uword *p; - - p = hash_get (utm->error_string_by_error_number, -error); - - if (p) - s = format (s, "%s", p[0]); - else - s = format (s, "%d", error); - return s; -} - -int -wait_for_state_change (udp_echo_main_t * utm, connection_state_t state) -{ -#if CLIB_DEBUG > 0 -#define TIMEOUT 600.0 -#else -#define TIMEOUT 600.0 -#endif - - f64 timeout = clib_time_now (&utm->clib_time) + TIMEOUT; - - while (clib_time_now (&utm->clib_time) < timeout) - { - if (utm->state == state) - return 0; - if (utm->state == STATE_FAILED) - return -1; - } - return -1; -} - -u64 server_bytes_received, server_bytes_sent; - -__clib_unused static void * -cut_through_thread_fn (void *arg) -{ - app_session_t *s; - svm_fifo_t *rx_fifo; - svm_fifo_t *tx_fifo; - u8 *my_copy_buffer = 0; - udp_echo_main_t *utm = &udp_echo_main; - i32 actual_transfer; - int rv, do_dequeue = 0; - u32 buffer_offset; - - while (utm->cut_through_session_index == ~0) - ; - - s = pool_elt_at_index (utm->sessions, utm->cut_through_session_index); - - rx_fifo = s->rx_fifo; - tx_fifo = s->tx_fifo; - - vec_validate (my_copy_buffer, 64 * 1024 - 1); - - while (1) - { - do - { - /* We read from the tx fifo and write to the rx fifo */ - if (utm->have_return || do_dequeue) - actual_transfer = svm_fifo_dequeue (rx_fifo, - vec_len (my_copy_buffer), - my_copy_buffer); - else - { - /* We don't do anything with the data, drop it */ - actual_transfer = svm_fifo_max_dequeue_cons (rx_fifo); - svm_fifo_dequeue_drop (rx_fifo, actual_transfer); - } - } - while (actual_transfer <= 0); - - server_bytes_received += actual_transfer; - - if (utm->have_return) - { - buffer_offset = 0; - while (actual_transfer > 0) - { - rv = svm_fifo_enqueue (tx_fifo, actual_transfer, - my_copy_buffer + buffer_offset); - if (rv > 0) - { - actual_transfer -= rv; - buffer_offset += rv; - server_bytes_sent += rv; - } - - } - } - if (PREDICT_FALSE (utm->time_to_stop)) - break; - } - - pthread_exit (0); -} - -static void -session_accepted_handler (session_accepted_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - udp_echo_main_t *utm = &udp_echo_main; - session_accepted_reply_msg_t *rmp; - svm_fifo_t *rx_fifo, *tx_fifo; - app_session_t *session; - static f64 start_time; - u32 session_index; - int rv = 0; - - if (start_time == 0.0) - start_time = clib_time_now (&utm->clib_time); - - utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address, - svm_msg_q_t *); - rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); - tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); - - pool_get (utm->sessions, session); - clib_memset (session, 0, sizeof (*session)); - session_index = session - utm->sessions; - session->session_index = session_index; - - rx_fifo->client_session_index = session_index; - tx_fifo->client_session_index = session_index; - session->rx_fifo = rx_fifo; - session->tx_fifo = tx_fifo; - clib_memcpy_fast (&session->transport.rmt_ip, &mp->rmt.ip, - sizeof (ip46_address_t)); - session->transport.is_ip4 = mp->rmt.is_ip4; - session->transport.rmt_port = mp->rmt.port; - - hash_set (utm->session_index_by_vpp_handles, mp->handle, session_index); - if (pool_elts (utm->sessions) && (pool_elts (utm->sessions) % 20000) == 0) - { - f64 now = clib_time_now (&utm->clib_time); - fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n", - pool_elts (utm->sessions), now - start_time, - (f64) pool_elts (utm->sessions) / (now - start_time)); - } - - app_alloc_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt, - SESSION_CTRL_EVT_ACCEPTED_REPLY); - rmp = (session_accepted_reply_msg_t *) app_evt->evt->data; - rmp->handle = mp->handle; - rmp->context = mp->context; - rmp->retval = rv; - app_send_ctrl_evt_to_vpp (utm->vpp_event_queue, app_evt); - - CLIB_MEMORY_BARRIER (); - utm->state = STATE_READY; -} - -static void -session_disconnected_handler (session_disconnected_msg_t * mp) -{ - app_session_evt_t _app_evt, *app_evt = &_app_evt; - udp_echo_main_t *utm = &udp_echo_main; - session_disconnected_reply_msg_t *rmp; - app_session_t *session; - uword *p; - int rv = 0; - - p = hash_get (utm->session_index_by_vpp_handles, mp->handle); - - if (p) - { - session = pool_elt_at_index (utm->sessions, p[0]); - hash_unset (utm->session_index_by_vpp_handles, mp->handle); - clib_warning ("disconnecting %u", session->session_index); - pool_put (utm->sessions, session); - } - else - { - clib_warning ("couldn't find session key %llx", mp->handle); - return; - } - - app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt, - SESSION_CTRL_EVT_DISCONNECTED_REPLY); - rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data; - rmp->retval = rv; - rmp->handle = mp->handle; - rmp->context = mp->context; - app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt); -} - -static void -session_connected_handler (session_connected_msg_t * mp) -{ - udp_echo_main_t *utm = &udp_echo_main; - unformat_input_t _input, *input = &_input; - session_endpoint_cfg_t _sep, *sep = &_sep; - app_session_t *session; - - ASSERT (utm->i_am_server == 0); - - if (mp->retval) - { - clib_warning ("failed connect"); - return; - } - - ASSERT (mp->server_rx_fifo && mp->server_tx_fifo); - - pool_get (utm->sessions, session); - session->session_index = session - utm->sessions; - session->rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *); - session->tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *); - - /* Cut-through case */ - if (mp->ct_rx_fifo) - { - clib_warning ("cut-through session"); - session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address, - svm_msg_q_t *); - utm->cut_through_session_index = session->session_index; - session->is_dgram = 0; - sleep (1); - session->rx_fifo->client_session_index = session->session_index; - session->tx_fifo->client_session_index = session->session_index; - /* TODO use ct fifos */ - } - else - { - utm->connected_session = session->session_index; - utm->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address, - svm_msg_q_t *); - - session->rx_fifo->client_session_index = session->session_index; - session->tx_fifo->client_session_index = session->session_index; - clib_memcpy_fast (&session->transport.lcl_ip, &mp->lcl.ip, - sizeof (ip46_address_t)); - session->transport.is_ip4 = mp->lcl.is_ip4; - session->transport.lcl_port = mp->lcl.port; - - unformat_init_vector (input, utm->connect_uri); - if (!unformat (input, "%U", unformat_uri, sep)) - { - clib_warning ("can't figure out remote ip and port"); - utm->state = STATE_FAILED; - unformat_free (input); - return; - } - unformat_free (input); - clib_memcpy_fast (&session->transport.rmt_ip, &sep->ip, - sizeof (ip46_address_t)); - session->transport.rmt_port = sep->port; - session->is_dgram = !utm->is_connected; - } - utm->state = STATE_READY; -} - -static void -session_bound_handler (session_bound_msg_t * mp) -{ - udp_echo_main_t *utm = &udp_echo_main; - svm_fifo_t *rx_fifo, *tx_fifo; - app_session_t *session; - u32 session_index; - - if (mp->retval) - { - clib_warning ("bind failed: %d", mp->retval); - utm->state = STATE_FAILED; - return; - } - - rx_fifo = uword_to_pointer (mp->rx_fifo, svm_fifo_t *); - tx_fifo = uword_to_pointer (mp->tx_fifo, svm_fifo_t *); - - pool_get (utm->sessions, session); - clib_memset (session, 0, sizeof (*session)); - session_index = session - utm->sessions; - - rx_fifo->client_session_index = session_index; - tx_fifo->client_session_index = session_index; - session->rx_fifo = rx_fifo; - session->tx_fifo = tx_fifo; - clib_memcpy_fast (&session->transport.lcl_ip, mp->lcl_ip, - sizeof (ip46_address_t)); - session->transport.is_ip4 = mp->lcl_is_ip4; - session->transport.lcl_port = mp->lcl_port; - session->vpp_evt_q = uword_to_pointer (mp->vpp_evt_q, svm_msg_q_t *); - - utm->state = utm->is_connected ? STATE_BOUND : STATE_READY; -} - -static void -handle_mq_event (session_event_t * e) -{ - switch (e->event_type) - { - case SESSION_CTRL_EVT_BOUND: - session_bound_handler ((session_bound_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_ACCEPTED: - session_accepted_handler ((session_accepted_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_CONNECTED: - session_connected_handler ((session_connected_msg_t *) e->data); - break; - case SESSION_CTRL_EVT_DISCONNECTED: - session_disconnected_handler ((session_disconnected_msg_t *) e->data); - break; - default: - clib_warning ("unhandled %u", e->event_type); - } -} - -static void -udp_client_send_connect (udp_echo_main_t * utm) -{ - vl_api_connect_uri_t *cmp; - cmp = vl_msg_api_alloc (sizeof (*cmp)); - clib_memset (cmp, 0, sizeof (*cmp)); - - cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI); - cmp->client_index = utm->my_client_index; - cmp->context = ntohl (0xfeedface); - memcpy (cmp->uri, utm->connect_uri, vec_len (utm->connect_uri)); - vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & cmp); -} - -static void -send_test_chunk (udp_echo_main_t * utm, app_session_t * s, u32 bytes) -{ - u64 test_buf_len, bytes_this_chunk, test_buf_offset; - - u8 *test_data = utm->connect_test_data; - u32 enq_space; - int written; - - test_buf_len = vec_len (test_data); - test_buf_offset = utm->bytes_sent % test_buf_len; - bytes_this_chunk = clib_min (test_buf_len - test_buf_offset, - utm->bytes_to_send); - enq_space = svm_fifo_max_enqueue_prod (s->tx_fifo); - bytes_this_chunk = clib_min (bytes_this_chunk, enq_space); - - written = app_send (s, test_data + test_buf_offset, bytes_this_chunk, - SVM_Q_WAIT); - if (written > 0) - { - utm->bytes_to_send -= written; - utm->bytes_sent += written; - } -} - -static void -recv_test_chunk (udp_echo_main_t * utm, app_session_t * s) -{ - app_recv (s, utm->rx_buf, vec_len (utm->rx_buf)); -} - -void -client_send_data (udp_echo_main_t * utm, u32 session_index) -{ - f64 start_time, end_time, delta; - app_session_t *session; - char *transfer_type; - u8 *test_data; - int i; - - vec_validate_aligned (utm->connect_test_data, 1024 * 1024 - 1, - CLIB_CACHE_LINE_BYTES); - for (i = 0; i < vec_len (utm->connect_test_data); i++) - utm->connect_test_data[i] = i & 0xff; - - test_data = utm->connect_test_data; - session = pool_elt_at_index (utm->sessions, session_index); - ASSERT (vec_len (test_data) > 0); - - utm->total_to_send = utm->bytes_to_send; - vec_validate (utm->rx_buf, vec_len (test_data) - 1); - start_time = clib_time_now (&utm->clib_time); - while (!utm->time_to_stop && utm->bytes_to_send) - { - send_test_chunk (utm, session, 0); - if (utm->have_return) - recv_test_chunk (utm, session); - if (utm->time_to_stop) - break; - } - - if (utm->have_return) - { - f64 timeout = clib_time_now (&utm->clib_time) + 5; - while (clib_time_now (&utm->clib_time) < timeout) - recv_test_chunk (utm, session); - } - - end_time = clib_time_now (&utm->clib_time); - delta = end_time - start_time; - transfer_type = utm->have_return ? "full-duplex" : "half-duplex"; - clib_warning ("%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds", - utm->total_to_send, utm->total_to_send / (1ULL << 20), - utm->total_to_send / (1ULL << 30), delta); - clib_warning ("%.2f bytes/second %s", ((f64) utm->total_to_send) / (delta), - transfer_type); - clib_warning ("%.4f gbit/second %s", - (((f64) utm->total_to_send * 8.0) / delta / 1e9), - transfer_type); -} - -static int -application_attach (udp_echo_main_t * utm) -{ - application_send_attach (utm); - if (wait_for_state_change (utm, STATE_ATTACHED)) - { - clib_warning ("timeout waiting for STATE_ATTACHED"); - return -1; - } - return 0; -} - -static void -client_test (udp_echo_main_t * utm) -{ - f64 start_time, timeout = 100.0; - svm_msg_q_msg_t msg; - session_event_t *e; - - if (application_attach (utm)) - return; - - udp_client_send_connect (utm); - - start_time = clib_time_now (&utm->clib_time); - while (pool_elts (utm->sessions) != 1 && utm->state != STATE_FAILED) - { - svm_msg_q_sub (utm->our_event_queue, &msg, SVM_Q_WAIT, 0); - e = svm_msg_q_msg_data (utm->our_event_queue, &msg); - handle_mq_event (e); - svm_msg_q_free_msg (utm->our_event_queue, &msg); - - if (clib_time_now (&utm->clib_time) - start_time >= timeout) - break; - } - - if (utm->cut_through_session_index != ~0) - client_send_data (utm, utm->cut_through_session_index); - else - client_send_data (utm, utm->connected_session); - - application_detach (utm); - wait_for_state_change (utm, STATE_DETACHED); -} - -static void -vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp) -{ - fifo_segment_create_args_t _a, *a = &_a; - udp_echo_main_t *utm = &udp_echo_main; - fifo_segment_main_t *sm = &utm->segment_main; - fifo_segment_t *seg; - int rv; - - clib_memset (a, 0, sizeof (*a)); - a->segment_name = (char *) mp->segment_name; - a->segment_size = mp->segment_size; - /* Attach to the segment vpp created */ - rv = fifo_segment_attach (sm, a); - if (rv) - { - clib_warning ("svm_fifo_segment_attach ('%s') failed", - mp->segment_name); - return; - } - seg = fifo_segment_get_segment (sm, a->new_segment_indices[0]); - clib_warning ("Mapped new segment '%s' size %d", seg->ssvm.name, - seg->ssvm.ssvm_size); - hash_set (utm->segments_table, clib_net_to_host_u64 (mp->segment_handle), - a->new_segment_indices[0]); -} - -static void -vl_api_unmap_segment_t_handler (vl_api_unmap_segment_t * mp) -{ - udp_echo_main_t *utm = &udp_echo_main; - fifo_segment_main_t *sm = &utm->segment_main; - fifo_segment_t *seg; - uword *seg_indexp; - u64 segment_handle; - - segment_handle = clib_net_to_host_u64 (mp->segment_handle); - seg_indexp = hash_get (utm->segments_table, segment_handle); - if (!seg_indexp) - { - clib_warning ("segment not mapped: %s", segment_handle); - return; - } - hash_unset (utm->segments_table, segment_handle); - seg = fifo_segment_get_segment (sm, (u32) seg_indexp[0]); - fifo_segment_delete (sm, seg); - clib_warning ("Unmapped segment '%s'", segment_handle); -} - -static void -vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp) -{ - udp_echo_main_t *utm = &udp_echo_main; - - if (mp->retval != 0) - clib_warning ("returned %d", ntohl (mp->retval)); - - utm->state = STATE_START; -} - -static void - vl_api_app_cut_through_registration_add_t_handler - (vl_api_app_cut_through_registration_add_t * mp) -{ - -} - -#define foreach_tcp_echo_msg \ -_(UNBIND_URI_REPLY, unbind_uri_reply) \ -_(MAP_ANOTHER_SEGMENT, map_another_segment) \ -_(UNMAP_SEGMENT, unmap_segment) \ -_(APPLICATION_ATTACH_REPLY, application_attach_reply) \ -_(APPLICATION_DETACH_REPLY, application_detach_reply) \ -_(APP_CUT_THROUGH_REGISTRATION_ADD, app_cut_through_registration_add) \ - -void -tcp_echo_api_hookup (udp_echo_main_t * utm) -{ -#define _(N,n) \ - vl_msg_api_set_handlers(VL_API_##N, #n, \ - vl_api_##n##_t_handler, \ - vl_noop_handler, \ - vl_api_##n##_t_endian, \ - vl_api_##n##_t_print, \ - sizeof(vl_api_##n##_t), 1); - foreach_tcp_echo_msg; -#undef _ - -} - -int -connect_to_vpp (char *name) -{ - udp_echo_main_t *utm = &udp_echo_main; - api_main_t *am = &api_main; - - if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0) - return -1; - - utm->vl_input_queue = am->shmem_hdr->vl_input_queue; - utm->my_client_index = am->my_client_index; - - return 0; -} - -void -vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...) -{ - clib_warning ("BUG"); -} - -static void -init_error_string_table (udp_echo_main_t * utm) -{ - utm->error_string_by_error_number = hash_create (0, sizeof (uword)); - -#define _(n,v,s) hash_set (utm->error_string_by_error_number, -v, s); - foreach_vnet_api_error; -#undef _ - - hash_set (utm->error_string_by_error_number, 99, "Misc"); -} - -void -server_handle_fifo_event_rx (udp_echo_main_t * utm, u32 session_index) -{ - svm_fifo_t *rx_fifo, *tx_fifo; - int n_read; - app_session_t *session; - int rv; - u32 max_dequeue, offset, max_transfer, rx_buf_len; - - session = pool_elt_at_index (utm->sessions, session_index); - rx_buf_len = vec_len (utm->rx_buf); - rx_fifo = session->rx_fifo; - tx_fifo = session->tx_fifo; - - - max_dequeue = svm_fifo_max_dequeue_cons (rx_fifo); - /* Allow enqueuing of a new event */ - svm_fifo_unset_event (rx_fifo); - - if (PREDICT_FALSE (!max_dequeue)) - return; - - /* Read the max_dequeue */ - do - { - max_transfer = clib_min (rx_buf_len, max_dequeue); - if (session->is_dgram) - n_read = app_recv_dgram_raw (rx_fifo, utm->rx_buf, max_transfer, - &session->transport, 0, 0); - else - n_read = app_recv_stream_raw (rx_fifo, utm->rx_buf, max_transfer, 0, - 0); - - if (n_read > 0) - max_dequeue -= n_read; - - /* Reflect if a non-drop session */ - if (utm->have_return && n_read > 0) - { - offset = 0; - do - { - rv = app_send (session, &utm->rx_buf[offset], n_read, - SVM_Q_WAIT); - if (rv > 0) - { - n_read -= rv; - offset += rv; - } - } - while ((rv <= 0 || n_read > 0) && !utm->time_to_stop); - - /* If event wasn't set, add one */ - if (svm_fifo_set_event (tx_fifo)) - app_send_io_evt_to_vpp (session->vpp_evt_q, - tx_fifo->master_session_index, - SESSION_IO_EVT_TX, SVM_Q_WAIT); - } - } - while ((n_read < 0 || max_dequeue > 0) && !utm->time_to_stop); -} - -static void -server_handle_event_queue (udp_echo_main_t * utm) -{ - session_event_t *e; - svm_msg_q_msg_t msg; - svm_msg_q_t *mq = utm->our_event_queue; - - while (utm->state != STATE_READY) - sleep (5); - - while (1) - { - if (svm_msg_q_sub (mq, &msg, SVM_Q_WAIT, 0)) - { - clib_warning ("svm msg q returned"); - continue; - } - e = svm_msg_q_msg_data (mq, &msg); - switch (e->event_type) - { - case SESSION_IO_EVT_RX: - server_handle_fifo_event_rx (utm, e->session_index); - break; - - default: - handle_mq_event (e); - break; - } - svm_msg_q_free_msg (mq, &msg); - if (PREDICT_FALSE (utm->time_to_stop == 1)) - return; - if (PREDICT_FALSE (utm->time_to_print_stats == 1)) - { - utm->time_to_print_stats = 0; - fformat (stdout, "%d connections\n", pool_elts (utm->sessions)); - } - } -} - -static void -server_unbind (udp_echo_main_t * utm) -{ - vl_api_unbind_uri_t *ump; - - ump = vl_msg_api_alloc (sizeof (*ump)); - clib_memset (ump, 0, sizeof (*ump)); - - ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI); - ump->client_index = utm->my_client_index; - memcpy (ump->uri, utm->listen_uri, vec_len (utm->listen_uri)); - vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & ump); -} - -static void -server_bind (udp_echo_main_t * utm) -{ - vl_api_bind_uri_t *bmp; - - bmp = vl_msg_api_alloc (sizeof (*bmp)); - clib_memset (bmp, 0, sizeof (*bmp)); - - bmp->_vl_msg_id = ntohs (VL_API_BIND_URI); - bmp->client_index = utm->my_client_index; - bmp->context = ntohl (0xfeedface); - memcpy (bmp->uri, utm->listen_uri, vec_len (utm->listen_uri)); - vl_msg_api_send_shmem (utm->vl_input_queue, (u8 *) & bmp); -} - -void -udp_server_test (udp_echo_main_t * utm) -{ - u8 wait_for_state = utm->is_connected ? STATE_BOUND : STATE_READY; - application_send_attach (utm); - - /* Bind to uri */ - server_bind (utm); - - if (wait_for_state_change (utm, wait_for_state)) - { - clib_warning ("timeout waiting for state change"); - return; - } - - server_handle_event_queue (utm); - - /* Cleanup */ - server_unbind (utm); - - if (wait_for_state_change (utm, STATE_START)) - { - clib_warning ("timeout waiting for STATE_START"); - return; - } - - application_detach (utm); - - fformat (stdout, "Test complete...\n"); -} - -int -main (int argc, char **argv) -{ - udp_echo_main_t *utm = &udp_echo_main; - fifo_segment_main_t *sm = &utm->segment_main; - u8 *uri = (u8 *) "udp://6.0.1.1/1234"; - unformat_input_t _argv, *a = &_argv; - int i_am_server = 1; - app_session_t *session; - u8 *chroot_prefix; - char *app_name; - u32 tmp; - int i; - - clib_mem_init_thread_safe (0, 256 << 20); - - fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20); - - vec_validate (utm->rx_buf, 128 << 10); - utm->session_index_by_vpp_handles = hash_create (0, sizeof (uword)); - utm->my_pid = getpid (); - utm->configured_segment_size = 1 << 20; - utm->have_return = 1; - utm->bytes_to_send = 1024; - utm->fifo_size = 128 << 10; - utm->cut_through_session_index = ~0; - clib_time_init (&utm->clib_time); - - init_error_string_table (utm); - unformat_init_command_line (a, argv); - - while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT) - { - if (unformat (a, "chroot prefix %s", &chroot_prefix)) - { - vl_set_memory_root_path ((char *) chroot_prefix); - } - else if (unformat (a, "uri %s", &uri)) - ; - else if (unformat (a, "segment-size %dM", &tmp)) - utm->configured_segment_size = tmp << 20; - else if (unformat (a, "segment-size %dG", &tmp)) - utm->configured_segment_size = tmp << 30; - else if (unformat (a, "server")) - i_am_server = 1; - else if (unformat (a, "client")) - i_am_server = 0; - else if (unformat (a, "no-return")) - utm->have_return = 0; - else if (unformat (a, "mbytes %d", &tmp)) - utm->bytes_to_send = (u64) tmp << 20; - else if (unformat (a, "fifo-size %d", &tmp)) - utm->fifo_size = tmp << 10; - else - { - fformat (stderr, "%s: usage [server|client]\n"); - exit (1); - } - } - - utm->i_am_server = i_am_server; - - setup_signal_handlers (); - tcp_echo_api_hookup (utm); - - if (i_am_server) - { - utm->listen_uri = format (0, "%s%c", uri, 0); - utm->is_connected = (utm->listen_uri[4] == 'c'); - app_name = "udp_echo_server"; - } - else - { - app_name = "udp_echo_client"; - utm->connect_uri = format (0, "%s%c", uri, 0); - utm->is_connected = (utm->connect_uri[4] == 'c'); - } - if (connect_to_vpp (app_name) < 0) - { - svm_region_exit (); - fformat (stderr, "Couldn't connect to vpe, exiting...\n"); - exit (1); - } - - if (i_am_server == 0) - { - client_test (utm); - goto done; - } - - /* $$$$ hack preallocation */ - for (i = 0; i < 200000; i++) - { - pool_get (utm->sessions, session); - clib_memset (session, 0, sizeof (*session)); - } - for (i = 0; i < 200000; i++) - pool_put_index (utm->sessions, i); - - udp_server_test (utm); - -done: - vl_client_disconnect_from_vlib (); - exit (0); -} - -#undef vl_api_version -#define vl_api_version(n,v) static u32 vpe_api_version = v; -#include -#undef vl_api_version - -void -vl_client_add_api_signatures (vl_api_memclnt_create_t * mp) -{ - /* - * Send the main API signature in slot 0. This bit of code must - * match the checks in ../vpe/api/api.c: vl_msg_api_version_check(). - */ - mp->api_versions[0] = clib_host_to_net_u32 (vpe_api_version); -} - -u32 -vl (void *p) -{ - return vec_len (p); -} - -/* - * fd.io coding-style-patch-verification: ON - * - * Local Variables: - * eval: (c-set-style "gnu") - * End: - */ diff --git a/src/plugins/hs_apps/vcl/sock_test.h b/src/plugins/hs_apps/vcl/sock_test.h new file mode 100644 index 00000000000..9f7f4379ce7 --- /dev/null +++ b/src/plugins/hs_apps/vcl/sock_test.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __sock_test_h__ +#define __sock_test_h__ + +#include +#include +#include +#include +#include + +#define SOCK_TEST_AF_UNIX_FILENAME "/tmp/ldp_server_af_unix_socket" +#define SOCK_TEST_MIXED_EPOLL_DATA "Hello, world! (over an AF_UNIX socket)" +#define SOCK_TEST_AF_UNIX_ACCEPT_DATA 0xaf0000af +#define SOCK_TEST_AF_UNIX_FD_MASK 0x00af0000 +#define SOCK_TEST_BANNER_STRING \ + "============================================\n" + +static inline int +sock_test_read (int fd, uint8_t *buf, uint32_t nbytes, + vcl_test_stats_t *stats) +{ + int rx_bytes, errno_val; + + do + { + if (stats) + stats->rx_xacts++; + rx_bytes = read (fd, buf, nbytes); + if (stats) + { + if ((rx_bytes == 0) || + ((rx_bytes < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))) + stats->rx_eagain++; + else if (rx_bytes < nbytes) + stats->rx_incomp++; + } + } + while ((rx_bytes == 0) || + ((rx_bytes < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))); + + if (rx_bytes < 0) + { + errno_val = errno; + perror ("ERROR in sock_test_read()"); + fprintf (stderr, "SOCK_TEST: ERROR: socket read " + "failed (errno = %d)!\n", errno_val); + errno = errno_val; + } + else if (stats) + stats->rx_bytes += rx_bytes; + + return (rx_bytes); +} + +static inline int +sock_test_write (int fd, uint8_t *buf, uint32_t nbytes, + vcl_test_stats_t *stats, uint32_t verbose) +{ + int tx_bytes = 0; + int nbytes_left = nbytes; + int rv, errno_val; + + do + { + if (stats) + stats->tx_xacts++; + rv = write (fd, buf, nbytes_left); + if (rv < 0) + { + if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) + { + if (stats) + stats->tx_eagain++; + continue; + } + else + break; + } + tx_bytes += rv; + + if (tx_bytes != nbytes) + { + nbytes_left = nbytes_left - rv; + if (stats) + stats->tx_incomp++; + if (verbose) + { + printf ("SOCK_TEST: WARNING: bytes written (%d) " + "!= bytes to write (%d)!\n", tx_bytes, nbytes); + } + } + + } while (tx_bytes != nbytes); + + if (tx_bytes < 0) + { + errno_val = errno; + perror ("ERROR in sock_test_write()"); + fprintf (stderr, "SOCK_TEST: ERROR: socket write failed " + "(errno = %d)!\n", errno_val); + } + else if (stats) + stats->tx_bytes += tx_bytes; + + return (tx_bytes); +} + +#endif /* __sock_test_h__ */ diff --git a/src/plugins/hs_apps/vcl/sock_test_client.c b/src/plugins/hs_apps/vcl/sock_test_client.c new file mode 100644 index 00000000000..ea89987f325 --- /dev/null +++ b/src/plugins/hs_apps/vcl/sock_test_client.c @@ -0,0 +1,1277 @@ +/* + * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef VCL_TEST +#include +#endif + +typedef struct +{ +#ifdef VCL_TEST + vppcom_endpt_t server_endpt; +#else + int af_unix_echo_tx; + int af_unix_echo_rx; +#endif + struct sockaddr_storage server_addr; + uint32_t server_addr_size; + uint32_t cfg_seq_num; + vcl_test_session_t ctrl_socket; + vcl_test_session_t *test_socket; + uint32_t num_test_sockets; + uint8_t dump_cfg; +} sock_client_main_t; + +sock_client_main_t vcl_client_main; + + +static int +sock_test_cfg_sync (vcl_test_session_t * socket) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + vcl_test_cfg_t *rl_cfg = (vcl_test_cfg_t *) socket->rxbuf; + int rx_bytes, tx_bytes; + + if (socket->cfg.verbose) + vcl_test_cfg_dump (&socket->cfg, 1 /* is_client */ ); + + ctrl->cfg.seq_num = ++scm->cfg_seq_num; + if (socket->cfg.verbose) + { + printf ("CLIENT (fd %d): Sending config sent to server.\n", socket->fd); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + tx_bytes = sock_test_write (socket->fd, (uint8_t *) & ctrl->cfg, + sizeof (ctrl->cfg), NULL, ctrl->cfg.verbose); + if (tx_bytes < 0) + { + fprintf (stderr, "CLIENT (fd %d): ERROR: write test cfg failed (%d)!\n", + socket->fd, tx_bytes); + return tx_bytes; + } + + rx_bytes = sock_test_read (socket->fd, (uint8_t *) socket->rxbuf, + sizeof (vcl_test_cfg_t), NULL); + if (rx_bytes < 0) + return rx_bytes; + + if (rl_cfg->magic != VCL_TEST_CFG_CTRL_MAGIC) + { + fprintf (stderr, "CLIENT (fd %d): ERROR: Bad server reply cfg " + "-- aborting!\n", socket->fd); + return -1; + } + if ((rx_bytes != sizeof (vcl_test_cfg_t)) + || !vcl_test_cfg_verify (rl_cfg, &ctrl->cfg)) + { + fprintf (stderr, "CLIENT (fd %d): ERROR: Invalid config received " + "from server!\n", socket->fd); + if (rx_bytes != sizeof (vcl_test_cfg_t)) + { + fprintf (stderr, "\tRx bytes %d != cfg size %lu\n", + rx_bytes, sizeof (vcl_test_cfg_t)); + } + else + { + vcl_test_cfg_dump (rl_cfg, 1 /* is_client */ ); + fprintf (stderr, "CLIENT (fd %d): Valid config sent to server.\n", + socket->fd); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + return -1; + } + else if (socket->cfg.verbose) + { + printf ("CLIENT (fd %d): Got config back from server.\n", socket->fd); + vcl_test_cfg_dump (rl_cfg, 1 /* is_client */ ); + } + ctrl->cfg.ctrl_handle = ((ctrl->cfg.ctrl_handle == ~0) ? + rl_cfg->ctrl_handle : ctrl->cfg.ctrl_handle); + + return 0; +} + +static void +echo_test_client () +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + vcl_test_session_t *tsock; + int rx_bytes, tx_bytes, nbytes; + uint32_t i, n; + int rv; + int nfds = 0; + fd_set wr_fdset, rd_fdset; + fd_set _wfdset, *wfdset = &_wfdset; + fd_set _rfdset, *rfdset = &_rfdset; + + FD_ZERO (&wr_fdset); + FD_ZERO (&rd_fdset); + memset (&ctrl->stats, 0, sizeof (ctrl->stats)); + ctrl->cfg.total_bytes = nbytes = strlen (ctrl->txbuf) + 1; + for (n = 0; n != ctrl->cfg.num_test_sessions; n++) + { + tsock = &scm->test_socket[n]; + tsock->cfg = ctrl->cfg; + vcl_test_session_buf_alloc (tsock); + if (sock_test_cfg_sync (tsock)) + return; + + memcpy (tsock->txbuf, ctrl->txbuf, nbytes); + memset (&tsock->stats, 0, sizeof (tsock->stats)); + + FD_SET (tsock->fd, &wr_fdset); + FD_SET (tsock->fd, &rd_fdset); + nfds = ((tsock->fd + 1) > nfds) ? (tsock->fd + 1) : nfds; + } + + nfds++; + clock_gettime (CLOCK_REALTIME, &ctrl->stats.start); + while (n) + { + _wfdset = wr_fdset; + _rfdset = rd_fdset; + +#ifdef VCL_TEST + rv = + vppcom_select (nfds, (unsigned long *) rfdset, + (unsigned long *) wfdset, NULL, 0); +#else + { + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 0; + rv = select (nfds, rfdset, wfdset, NULL, &timeout); + } +#endif + if (rv < 0) + { + perror ("select()"); + fprintf (stderr, "\nCLIENT: ERROR: select() failed -- " + "aborting test!\n"); + return; + } + else if (rv == 0) + continue; + + for (i = 0; i < ctrl->cfg.num_test_sessions; i++) + { + tsock = &scm->test_socket[i]; + if (!((tsock->stats.stop.tv_sec == 0) && + (tsock->stats.stop.tv_nsec == 0))) + continue; + + if (FD_ISSET (tsock->fd, wfdset) && + (tsock->stats.tx_bytes < ctrl->cfg.total_bytes)) + + { + tx_bytes = + sock_test_write (tsock->fd, (uint8_t *) tsock->txbuf, nbytes, + &tsock->stats, ctrl->cfg.verbose); + if (tx_bytes < 0) + { + fprintf (stderr, "\nCLIENT: ERROR: sock_test_write(%d) " + "failed -- aborting test!\n", tsock->fd); + return; + } + + printf ("CLIENT (fd %d): TX (%d bytes) - '%s'\n", + tsock->fd, tx_bytes, tsock->txbuf); + } + + if ((FD_ISSET (tsock->fd, rfdset)) && + (tsock->stats.rx_bytes < ctrl->cfg.total_bytes)) + { + rx_bytes = + sock_test_read (tsock->fd, (uint8_t *) tsock->rxbuf, + nbytes, &tsock->stats); + if (rx_bytes > 0) + { + printf ("CLIENT (fd %d): RX (%d bytes) - '%s'\n", + tsock->fd, rx_bytes, tsock->rxbuf); + + if (tsock->stats.rx_bytes != tsock->stats.tx_bytes) + printf ("CLIENT: WARNING: bytes read (%lu) " + "!= bytes written (%lu)!\n", + tsock->stats.rx_bytes, tsock->stats.tx_bytes); + } + } + + if (tsock->stats.rx_bytes >= ctrl->cfg.total_bytes) + { + clock_gettime (CLOCK_REALTIME, &tsock->stats.stop); + n--; + } + } + } + clock_gettime (CLOCK_REALTIME, &ctrl->stats.stop); + +#ifndef VCL_TEST + { + int fd, errno_val; + struct sockaddr_un serveraddr; + uint8_t buffer[256]; + size_t nbytes = strlen (SOCK_TEST_MIXED_EPOLL_DATA) + 1; + struct timeval timeout; + + /* Open AF_UNIX socket and send an echo to test mixed epoll on server. + */ + fd = socket (AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) + { + errno_val = errno; + perror ("ERROR in echo_test_client(): socket(AF_UNIX) failed"); + fprintf (stderr, + "CLIENT: ERROR: socket(AF_UNIX, SOCK_STREAM, 0) failed " + "(errno = %d)!\n", errno_val); + goto out; + } + memset (&serveraddr, 0, sizeof (serveraddr)); + serveraddr.sun_family = AF_UNIX; + strcpy (serveraddr.sun_path, SOCK_TEST_AF_UNIX_FILENAME); + rv = connect (fd, (struct sockaddr *) &serveraddr, SUN_LEN (&serveraddr)); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in echo_test_client(): connect() failed"); + fprintf (stderr, "CLIENT: ERROR: connect(fd %d, \"%s\", %lu) " + "failed (errno = %d)!\n", fd, SOCK_TEST_AF_UNIX_FILENAME, + SUN_LEN (&serveraddr), errno_val); + goto done; + } + + scm->af_unix_echo_tx++; + strcpy ((char *) buffer, SOCK_TEST_MIXED_EPOLL_DATA); + timeout.tv_sec = 0; + timeout.tv_usec = 250000; + select (0, NULL, NULL, NULL, &timeout); /* delay .25 secs */ + rv = write (fd, buffer, nbytes); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in echo_test_client(): write() failed"); + fprintf (stderr, "CLIENT: ERROR: write(fd %d, \"%s\", %lu) " + "failed (errno = %d)!\n", fd, buffer, nbytes, errno_val); + goto done; + } + else if (rv < nbytes) + { + fprintf (stderr, "CLIENT: ERROR: write(fd %d, \"%s\", %lu) " + "returned %d!\n", fd, buffer, nbytes, rv); + goto done; + } + + printf ("CLIENT (AF_UNIX): TX (%d bytes) - '%s'\n", rv, buffer); + memset (buffer, 0, sizeof (buffer)); + rv = read (fd, buffer, nbytes); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in echo_test_client(): read() failed"); + fprintf (stderr, "CLIENT: ERROR: read(fd %d, %p, %lu) " + "failed (errno = %d)!\n", fd, buffer, nbytes, errno_val); + goto done; + } + else if (rv < nbytes) + { + fprintf (stderr, "CLIENT: ERROR: read(fd %d, %p, %lu) " + "returned %d!\n", fd, buffer, nbytes, rv); + goto done; + } + + if (!strncmp (SOCK_TEST_MIXED_EPOLL_DATA, (const char *) buffer, nbytes)) + { + printf ("CLIENT (AF_UNIX): RX (%d bytes) - '%s'\n", rv, buffer); + scm->af_unix_echo_rx++; + } + else + printf ("CLIENT (AF_UNIX): ERROR: RX (%d bytes) - '%s'\n", rv, buffer); + + done: + close (fd); + out: + ; + } +#endif + + for (i = 0; i < ctrl->cfg.num_test_sessions; i++) + { + tsock = &scm->test_socket[i]; + tsock->stats.start = ctrl->stats.start; + + if (ctrl->cfg.verbose) + { + static char buf[64]; + + sprintf (buf, "CLIENT (fd %d) RESULTS", tsock->fd); + vcl_test_stats_dump (buf, &tsock->stats, + 1 /* show_rx */ , 1 /* show tx */ , + ctrl->cfg.verbose); + } + + vcl_test_stats_accumulate (&ctrl->stats, &tsock->stats); + } + + if (ctrl->cfg.verbose) + { + vcl_test_stats_dump ("CLIENT RESULTS", &ctrl->stats, + 1 /* show_rx */ , 1 /* show tx */ , + ctrl->cfg.verbose); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + + if (ctrl->cfg.verbose > 1) + { + printf (" ctrl socket info\n" + VCL_TEST_SEPARATOR_STRING + " fd: %d (0x%08x)\n" + " rxbuf: %p\n" + " rxbuf size: %u (0x%08x)\n" + " txbuf: %p\n" + " txbuf size: %u (0x%08x)\n" + VCL_TEST_SEPARATOR_STRING, + ctrl->fd, (uint32_t) ctrl->fd, + ctrl->rxbuf, ctrl->rxbuf_size, ctrl->rxbuf_size, + ctrl->txbuf, ctrl->txbuf_size, ctrl->txbuf_size); + } + } +} + +static void +stream_test_client (vcl_test_t test) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + vcl_test_session_t *tsock; + int tx_bytes; + uint32_t i, n; + int rv; + int nfds = 0; + fd_set wr_fdset, rd_fdset; + fd_set _wfdset, *wfdset = &_wfdset; + fd_set _rfdset, *rfdset = (test == VCL_TEST_TYPE_BI) ? &_rfdset : 0; + + ctrl->cfg.total_bytes = ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + ctrl->cfg.ctrl_handle = ~0; + + printf ("\n" SOCK_TEST_BANNER_STRING + "CLIENT (fd %d): %s-directional Stream Test!\n\n" + "CLIENT (fd %d): Sending config to server on ctrl socket...\n", + ctrl->fd, test == VCL_TEST_TYPE_BI ? "Bi" : "Uni", ctrl->fd); + + if (sock_test_cfg_sync (ctrl)) + { + fprintf (stderr, "CLIENT: ERROR: test cfg sync failed -- aborting!"); + return; + } + + FD_ZERO (&wr_fdset); + FD_ZERO (&rd_fdset); + memset (&ctrl->stats, 0, sizeof (ctrl->stats)); + for (n = 0; n != ctrl->cfg.num_test_sessions; n++) + { + tsock = &scm->test_socket[n]; + tsock->cfg = ctrl->cfg; + vcl_test_session_buf_alloc (tsock); + printf ("CLIENT (fd %d): Sending config to server on " + "test socket %d...\n", tsock->fd, n); + sock_test_cfg_sync (tsock); + + /* Fill payload with incrementing uint32's */ + for (i = 0; i < tsock->txbuf_size; i++) + tsock->txbuf[i] = i & 0xff; + + memset (&tsock->stats, 0, sizeof (tsock->stats)); + FD_SET (tsock->fd, &wr_fdset); + FD_SET (tsock->fd, &rd_fdset); + nfds = ((tsock->fd + 1) > nfds) ? (tsock->fd + 1) : nfds; + } + + nfds++; + clock_gettime (CLOCK_REALTIME, &ctrl->stats.start); + while (n) + { + _wfdset = wr_fdset; + _rfdset = rd_fdset; + +#ifdef VCL_TEST + rv = + vppcom_select (nfds, (unsigned long *) rfdset, + (unsigned long *) wfdset, NULL, 0); +#else + { + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 0; + rv = select (nfds, rfdset, wfdset, NULL, &timeout); + } +#endif + if (rv < 0) + { + perror ("select()"); + fprintf (stderr, "\nCLIENT: ERROR: select() failed -- " + "aborting test!\n"); + return; + } + else if (rv == 0) + continue; + + for (i = 0; i < ctrl->cfg.num_test_sessions; i++) + { + tsock = &scm->test_socket[i]; + if (!((tsock->stats.stop.tv_sec == 0) && + (tsock->stats.stop.tv_nsec == 0))) + continue; + + if ((test == VCL_TEST_TYPE_BI) && + FD_ISSET (tsock->fd, rfdset) && + (tsock->stats.rx_bytes < ctrl->cfg.total_bytes)) + { + (void) sock_test_read (tsock->fd, + (uint8_t *) tsock->rxbuf, + tsock->rxbuf_size, &tsock->stats); + } + + if (FD_ISSET (tsock->fd, wfdset) && + (tsock->stats.tx_bytes < ctrl->cfg.total_bytes)) + { + tx_bytes = sock_test_write (tsock->fd, (uint8_t *) tsock->txbuf, + ctrl->cfg.txbuf_size, &tsock->stats, + ctrl->cfg.verbose); + if (tx_bytes < 0) + { + fprintf (stderr, "\nCLIENT: ERROR: sock_test_write(%d) " + "failed -- aborting test!\n", tsock->fd); + return; + } + } + + if (((test == VCL_TEST_TYPE_UNI) && + (tsock->stats.tx_bytes >= ctrl->cfg.total_bytes)) || + ((test == VCL_TEST_TYPE_BI) && + (tsock->stats.rx_bytes >= ctrl->cfg.total_bytes))) + { + clock_gettime (CLOCK_REALTIME, &tsock->stats.stop); + n--; + } + } + } + clock_gettime (CLOCK_REALTIME, &ctrl->stats.stop); + + printf ("CLIENT (fd %d): Sending config to server on ctrl socket...\n", + ctrl->fd); + + if (sock_test_cfg_sync (ctrl)) + { + fprintf (stderr, "CLIENT: ERROR: test cfg sync failed -- aborting!"); + return; + } + + for (i = 0; i < ctrl->cfg.num_test_sessions; i++) + { + tsock = &scm->test_socket[i]; + + if (ctrl->cfg.verbose) + { + static char buf[64]; + + sprintf (buf, "CLIENT (fd %d) RESULTS", tsock->fd); + vcl_test_stats_dump (buf, &tsock->stats, + test == VCL_TEST_TYPE_BI /* show_rx */ , + 1 /* show tx */ , ctrl->cfg.verbose); + } + + vcl_test_stats_accumulate (&ctrl->stats, &tsock->stats); + } + + vcl_test_stats_dump ("CLIENT RESULTS", &ctrl->stats, + test == VCL_TEST_TYPE_BI /* show_rx */ , + 1 /* show tx */ , ctrl->cfg.verbose); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + + if (ctrl->cfg.verbose) + { + printf (" ctrl socket info\n" + VCL_TEST_SEPARATOR_STRING + " fd: %d (0x%08x)\n" + " rxbuf: %p\n" + " rxbuf size: %u (0x%08x)\n" + " txbuf: %p\n" + " txbuf size: %u (0x%08x)\n" + VCL_TEST_SEPARATOR_STRING, + ctrl->fd, (uint32_t) ctrl->fd, + ctrl->rxbuf, ctrl->rxbuf_size, ctrl->rxbuf_size, + ctrl->txbuf, ctrl->txbuf_size, ctrl->txbuf_size); + } + + ctrl->cfg.test = VCL_TEST_TYPE_ECHO; + if (sock_test_cfg_sync (ctrl)) + fprintf (stderr, "CLIENT: ERROR: post-test cfg sync failed!"); + + printf ("CLIENT (fd %d): %s-directional Stream Test Complete!\n" + SOCK_TEST_BANNER_STRING "\n", ctrl->fd, + test == VCL_TEST_TYPE_BI ? "Bi" : "Uni"); +} + +static void +exit_client (void) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + vcl_test_session_t *tsock; + int i; + +#ifndef VCL_TEST + printf ("CLIENT: af_unix_echo_tx %d, af_unix_echo_rx %d\n", + scm->af_unix_echo_tx, scm->af_unix_echo_rx); +#endif + for (i = 0; i < ctrl->cfg.num_test_sessions; i++) + { + tsock = &scm->test_socket[i]; + tsock->cfg.test = VCL_TEST_TYPE_EXIT; + + /* coverity[COPY_PASTE_ERROR] */ + if (ctrl->cfg.verbose) + { + printf ("\nCLIENT (fd %d): Sending exit cfg to server...\n", + tsock->fd); + vcl_test_cfg_dump (&tsock->cfg, 1 /* is_client */ ); + } + (void) sock_test_write (tsock->fd, (uint8_t *) & tsock->cfg, + sizeof (tsock->cfg), &tsock->stats, + ctrl->cfg.verbose); + } + + ctrl->cfg.test = VCL_TEST_TYPE_EXIT; + if (ctrl->cfg.verbose) + { + printf ("\nCLIENT (fd %d): Sending exit cfg to server...\n", ctrl->fd); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + (void) sock_test_write (ctrl->fd, (uint8_t *) & ctrl->cfg, + sizeof (ctrl->cfg), &ctrl->stats, + ctrl->cfg.verbose); + printf ("\nCLIENT: So long and thanks for all the fish!\n\n"); + sleep (1); +} + +static int +sock_test_connect_test_sockets (uint32_t num_test_sockets) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + vcl_test_session_t *tsock; + int i, rv, errno_val; + + if (num_test_sockets < 1) + { + errno = EINVAL; + return -1; + } + + if (num_test_sockets < scm->num_test_sockets) + { + for (i = scm->num_test_sockets - 1; i >= num_test_sockets; i--) + { + tsock = &scm->test_socket[i]; +#ifdef VCL_TEST + vppcom_session_close (tsock->fd); +#else + close (tsock->fd); +#endif + free (tsock->txbuf); + free (tsock->rxbuf); + } + } + + else if (num_test_sockets > scm->num_test_sockets) + { + tsock = realloc (scm->test_socket, + sizeof (vcl_test_session_t) * num_test_sockets); + if (!tsock) + { + errno_val = errno; + perror ("ERROR in sock_test_connect_test_sockets()"); + fprintf (stderr, "CLIENT: ERROR: socket failed (errno = %d)!\n", + errno_val); + return -1; + } + + if (!scm->test_socket) + memset (tsock, 0, sizeof (*tsock)); + + scm->test_socket = tsock; + for (i = scm->num_test_sockets; i < num_test_sockets; i++) + { + tsock = &scm->test_socket[i]; +#ifdef VCL_TEST + tsock->fd = vppcom_session_create (ctrl->cfg.transport_udp ? + VPPCOM_PROTO_UDP : + VPPCOM_PROTO_TCP, + 1 /* is_nonblocking */ ); + if (tsock->fd < 0) + { + errno = -tsock->fd; + tsock->fd = -1; + } +#else + tsock->fd = socket (ctrl->cfg.address_ip6 ? AF_INET6 : AF_INET, + ctrl->cfg.transport_udp ? + SOCK_DGRAM : SOCK_STREAM, 0); +#endif + if (tsock->fd < 0) + { + errno_val = errno; + perror ("ERROR in sock_test_connect_test_sockets()"); + fprintf (stderr, "CLIENT: ERROR: socket failed (errno = %d)!\n", + errno_val); + return tsock->fd; + } + if (fcntl (tsock->fd, F_SETFL, O_NONBLOCK) < 0) + { + errno_val = errno; + perror ("ERROR in sock_test_connect_test_sockets()"); + fprintf (stderr, "CLIENT: ERROR: fcntl failed (errno = %d)!\n", + errno_val); + return -1; + } + +#ifdef VCL_TEST + rv = vppcom_session_connect (tsock->fd, &scm->server_endpt); + if (rv) + { + errno = -rv; + rv = -1; + } +#else + rv = + connect (tsock->fd, (struct sockaddr *) &scm->server_addr, + scm->server_addr_size); +#endif + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in sock_test_connect_test_sockets()"); + fprintf (stderr, "CLIENT: ERROR: connect failed " + "(errno = %d)!\n", errno_val); + return -1; + } + tsock->cfg = ctrl->cfg; + vcl_test_session_buf_alloc (tsock); + sock_test_cfg_sync (tsock); + + printf ("CLIENT (fd %d): Test socket %d connected.\n", + tsock->fd, i); + } + } + + scm->num_test_sockets = num_test_sockets; + printf ("CLIENT: All sockets (%d) connected!\n", scm->num_test_sockets + 1); + return 0; +} + +static void +dump_help (void) +{ +#define INDENT "\n " + + printf ("CLIENT: Test configuration commands:" + INDENT VCL_TEST_TOKEN_HELP + "\t\t\tDisplay help." + INDENT VCL_TEST_TOKEN_EXIT + "\t\t\tExit test client & server." + INDENT VCL_TEST_TOKEN_SHOW_CFG + "\t\t\tShow the current test cfg." + INDENT VCL_TEST_TOKEN_RUN_UNI + "\t\t\tRun the Uni-directional test." + INDENT VCL_TEST_TOKEN_RUN_BI + "\t\t\tRun the Bi-directional test." + INDENT VCL_TEST_TOKEN_VERBOSE + "\t\t\tToggle verbose setting." + INDENT VCL_TEST_TOKEN_RXBUF_SIZE + "\tRx buffer size (bytes)." + INDENT VCL_TEST_TOKEN_TXBUF_SIZE + "\tTx buffer size (bytes)." + INDENT VCL_TEST_TOKEN_NUM_WRITES + "<# of writes>\tNumber of txbuf writes to server." "\n"); +} + +static void +cfg_txbuf_size_set (void) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_TXBUF_SIZE); + uint64_t txbuf_size = strtoull ((const char *) p, NULL, 10); + + if (txbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->cfg.txbuf_size = txbuf_size; + ctrl->cfg.total_bytes = ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 0 /* is_rxbuf */ , + (uint8_t **) & ctrl->txbuf, &ctrl->txbuf_size); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + fprintf (stderr, "CLIENT: ERROR: Invalid txbuf size (%lu) < " + "minimum buf size (%u)!\n", + txbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); +} + +static void +cfg_num_writes_set (void) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_NUM_WRITES); + uint32_t num_writes = strtoul ((const char *) p, NULL, 10); + + if (num_writes > 0) + { + ctrl->cfg.num_writes = num_writes; + ctrl->cfg.total_bytes = ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + { + fprintf (stderr, "CLIENT: ERROR: invalid num writes: %u\n", num_writes); + } +} + +static void +cfg_num_test_sockets_set (void) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_NUM_TEST_SESS); + uint32_t num_test_sockets = strtoul ((const char *) p, NULL, 10); + + if ((num_test_sockets > 0) && + (num_test_sockets <= VCL_TEST_CFG_MAX_TEST_SESS)) + { + ctrl->cfg.num_test_sessions = num_test_sockets; + sock_test_connect_test_sockets (num_test_sockets); + + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + { + fprintf (stderr, "CLIENT: ERROR: invalid num test sockets: " + "%u, (%d max)\n", + num_test_sockets, VCL_TEST_CFG_MAX_TEST_SESS); + } +} + +static void +cfg_rxbuf_size_set (void) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_RXBUF_SIZE); + uint64_t rxbuf_size = strtoull ((const char *) p, NULL, 10); + + if (rxbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->cfg.rxbuf_size = rxbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 1 /* is_rxbuf */ , + (uint8_t **) & ctrl->rxbuf, &ctrl->rxbuf_size); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + fprintf (stderr, "CLIENT: ERROR: Invalid rxbuf size (%lu) < " + "minimum buf size (%u)!\n", + rxbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); +} + +static void +cfg_verbose_toggle (void) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + + ctrl->cfg.verbose = ctrl->cfg.verbose ? 0 : 1; + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + +} + +static vcl_test_t +parse_input () +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + vcl_test_t rv = VCL_TEST_TYPE_NONE; + + if (!strncmp (VCL_TEST_TOKEN_EXIT, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_EXIT))) + rv = VCL_TEST_TYPE_EXIT; + + else if (!strncmp (VCL_TEST_TOKEN_HELP, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_HELP))) + dump_help (); + + else if (!strncmp (VCL_TEST_TOKEN_SHOW_CFG, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_SHOW_CFG))) + scm->dump_cfg = 1; + + else if (!strncmp (VCL_TEST_TOKEN_VERBOSE, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_VERBOSE))) + cfg_verbose_toggle (); + + else if (!strncmp (VCL_TEST_TOKEN_TXBUF_SIZE, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_TXBUF_SIZE))) + cfg_txbuf_size_set (); + + else if (!strncmp (VCL_TEST_TOKEN_NUM_TEST_SESS, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_NUM_TEST_SESS))) + cfg_num_test_sockets_set (); + + else if (!strncmp (VCL_TEST_TOKEN_NUM_WRITES, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_NUM_WRITES))) + cfg_num_writes_set (); + + else if (!strncmp (VCL_TEST_TOKEN_RXBUF_SIZE, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_RXBUF_SIZE))) + cfg_rxbuf_size_set (); + + else if (!strncmp (VCL_TEST_TOKEN_RUN_UNI, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_RUN_UNI))) + rv = ctrl->cfg.test = VCL_TEST_TYPE_UNI; + + else if (!strncmp (VCL_TEST_TOKEN_RUN_BI, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_RUN_BI))) + rv = ctrl->cfg.test = VCL_TEST_TYPE_BI; + + else + rv = VCL_TEST_TYPE_ECHO; + + return rv; +} + +void +print_usage_and_exit (void) +{ + fprintf (stderr, + "sock_test_client [OPTIONS] \n" + " OPTIONS\n" + " -h Print this message and exit.\n" + " -6 Use IPv6\n" + " -u Use UDP transport layer\n" + " -c Print test config before test.\n" + " -w Write test results to .\n" + " -X Exit after running test.\n" + " -E Run Echo test.\n" + " -N Test Cfg: number of writes.\n" + " -R Test Cfg: rx buffer size.\n" + " -T Test Cfg: tx buffer size.\n" + " -U Run Uni-directional test.\n" + " -B Run Bi-directional test.\n" + " -V Verbose mode.\n"); + exit (1); +} + +int +main (int argc, char **argv) +{ + sock_client_main_t *scm = &vcl_client_main; + vcl_test_session_t *ctrl = &scm->ctrl_socket; + int c, rv, errno_val; + vcl_test_t post_test = VCL_TEST_TYPE_NONE; + + vcl_test_cfg_init (&ctrl->cfg); + vcl_test_session_buf_alloc (ctrl); + + opterr = 0; + while ((c = getopt (argc, argv, "chn:w:XE:I:N:R:T:UBV6D")) != -1) + switch (c) + { + case 'c': + scm->dump_cfg = 1; + break; + + case 's': + if (sscanf (optarg, "0x%x", &ctrl->cfg.num_test_sessions) != 1) + if (sscanf (optarg, "%u", &ctrl->cfg.num_test_sessions) != 1) + { + fprintf (stderr, "CLIENT: ERROR: Invalid value for " + "option -%c!\n", c); + print_usage_and_exit (); + } + if (!ctrl->cfg.num_test_sessions || + (ctrl->cfg.num_test_sessions > FD_SETSIZE)) + { + fprintf (stderr, "CLIENT: ERROR: Invalid number of " + "sockets (%d) specified for option -%c!\n" + " Valid range is 1 - %d\n", + ctrl->cfg.num_test_sessions, c, FD_SETSIZE); + print_usage_and_exit (); + } + break; + + case 'w': + fprintf (stderr, "CLIENT: Writing test results to files is TBD.\n"); + break; + + case 'X': + post_test = VCL_TEST_TYPE_EXIT; + break; + + case 'E': + if (strlen (optarg) > ctrl->txbuf_size) + { + fprintf (stderr, "CLIENT: ERROR: Option -%c value " + "larger than txbuf size (%d)!\n", + optopt, ctrl->txbuf_size); + print_usage_and_exit (); + } + strcpy (ctrl->txbuf, optarg); + ctrl->cfg.test = VCL_TEST_TYPE_ECHO; + break; + + case 'I': + if (sscanf (optarg, "0x%x", &ctrl->cfg.num_test_sessions) != 1) + if (sscanf (optarg, "%d", &ctrl->cfg.num_test_sessions) != 1) + { + fprintf (stderr, "CLIENT: ERROR: Invalid value for " + "option -%c!\n", c); + print_usage_and_exit (); + } + if (ctrl->cfg.num_test_sessions > VCL_TEST_CFG_MAX_TEST_SESS) + { + fprintf (stderr, "CLIENT: ERROR: value greater than max " + "number test sockets (%d)!", VCL_TEST_CFG_MAX_TEST_SESS); + print_usage_and_exit (); + } + break; + + case 'N': + if (sscanf (optarg, "0x%lx", &ctrl->cfg.num_writes) != 1) + if (sscanf (optarg, "%ld", &ctrl->cfg.num_writes) != 1) + { + fprintf (stderr, "CLIENT: ERROR: Invalid value for " + "option -%c!\n", c); + print_usage_and_exit (); + } + ctrl->cfg.total_bytes = ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + break; + + case 'R': + if (sscanf (optarg, "0x%lx", &ctrl->cfg.rxbuf_size) != 1) + if (sscanf (optarg, "%ld", &ctrl->cfg.rxbuf_size) != 1) + { + fprintf (stderr, "CLIENT: ERROR: Invalid value for " + "option -%c!\n", c); + print_usage_and_exit (); + } + if (ctrl->cfg.rxbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->rxbuf_size = ctrl->cfg.rxbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 1 /* is_rxbuf */ , + (uint8_t **) & ctrl->rxbuf, + &ctrl->rxbuf_size); + } + else + { + fprintf (stderr, "CLIENT: ERROR: rxbuf size (%lu) " + "less than minumum (%u)\n", + ctrl->cfg.rxbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); + print_usage_and_exit (); + } + + break; + + case 'T': + if (sscanf (optarg, "0x%lx", &ctrl->cfg.txbuf_size) != 1) + if (sscanf (optarg, "%ld", &ctrl->cfg.txbuf_size) != 1) + { + fprintf (stderr, "CLIENT: ERROR: Invalid value " + "for option -%c!\n", c); + print_usage_and_exit (); + } + if (ctrl->cfg.txbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->txbuf_size = ctrl->cfg.txbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 0 /* is_rxbuf */ , + (uint8_t **) & ctrl->txbuf, + &ctrl->txbuf_size); + ctrl->cfg.total_bytes = + ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + } + else + { + fprintf (stderr, "CLIENT: ERROR: txbuf size (%lu) " + "less than minumum (%u)!\n", + ctrl->cfg.txbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); + print_usage_and_exit (); + } + break; + + case 'U': + ctrl->cfg.test = VCL_TEST_TYPE_UNI; + break; + + case 'B': + ctrl->cfg.test = VCL_TEST_TYPE_BI; + break; + + case 'V': + ctrl->cfg.verbose = 1; + break; + + case '6': + ctrl->cfg.address_ip6 = 1; + break; + + case 'D': + ctrl->cfg.transport_udp = 1; + break; + + case '?': + switch (optopt) + { + case 'E': + case 'I': + case 'N': + case 'R': + case 'T': + case 'w': + fprintf (stderr, "CLIENT: ERROR: Option -%c " + "requires an argument.\n", optopt); + break; + + default: + if (isprint (optopt)) + fprintf (stderr, "CLIENT: ERROR: Unknown " + "option `-%c'.\n", optopt); + else + fprintf (stderr, "CLIENT: ERROR: Unknown " + "option character `\\x%x'.\n", optopt); + } + /* fall thru */ + case 'h': + default: + print_usage_and_exit (); + } + + if (argc < (optind + 2)) + { + fprintf (stderr, "CLIENT: ERROR: Insufficient number of arguments!\n"); + print_usage_and_exit (); + } + +#ifdef VCL_TEST + ctrl->fd = vppcom_app_create ("vcl_test_client"); + if (ctrl->fd < 0) + { + errno = -ctrl->fd; + ctrl->fd = -1; + } + else + { + ctrl->fd = vppcom_session_create (ctrl->cfg.transport_udp ? + VPPCOM_PROTO_UDP : + VPPCOM_PROTO_TCP, + 0 /* is_nonblocking */ ); + if (ctrl->fd < 0) + { + errno = -ctrl->fd; + ctrl->fd = -1; + } + } +#else + ctrl->fd = socket (ctrl->cfg.address_ip6 ? AF_INET6 : AF_INET, + ctrl->cfg.transport_udp ? SOCK_DGRAM : SOCK_STREAM, 0); +#endif + + if (ctrl->fd < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "CLIENT: ERROR: socket " + "failed (errno = %d)!\n", errno_val); + return ctrl->fd; + } + + memset (&scm->server_addr, 0, sizeof (scm->server_addr)); + if (ctrl->cfg.address_ip6) + { + struct sockaddr_in6 *server_addr = + (struct sockaddr_in6 *) &scm->server_addr; + scm->server_addr_size = sizeof (*server_addr); + server_addr->sin6_family = AF_INET6; + inet_pton (AF_INET6, argv[optind++], &(server_addr->sin6_addr)); + server_addr->sin6_port = htons (atoi (argv[optind])); + } + else + { + struct sockaddr_in *server_addr = + (struct sockaddr_in *) &scm->server_addr; + scm->server_addr_size = sizeof (*server_addr); + server_addr->sin_family = AF_INET; + inet_pton (AF_INET, argv[optind++], &(server_addr->sin_addr)); + server_addr->sin_port = htons (atoi (argv[optind])); + } + +#ifdef VCL_TEST + if (ctrl->cfg.address_ip6) + { + struct sockaddr_in6 *server_addr = + (struct sockaddr_in6 *) &scm->server_addr; + scm->server_endpt.is_ip4 = 0; + scm->server_endpt.ip = (uint8_t *) & server_addr->sin6_addr; + scm->server_endpt.port = (uint16_t) server_addr->sin6_port; + } + else + { + struct sockaddr_in *server_addr = + (struct sockaddr_in *) &scm->server_addr; + scm->server_endpt.is_ip4 = 1; + scm->server_endpt.ip = (uint8_t *) & server_addr->sin_addr; + scm->server_endpt.port = (uint16_t) server_addr->sin_port; + } +#endif + + do + { + printf ("\nCLIENT: Connecting to server...\n"); + +#ifdef VCL_TEST + rv = vppcom_session_connect (ctrl->fd, &scm->server_endpt); + if (rv) + { + errno = -rv; + rv = -1; + } +#else + rv = + connect (ctrl->fd, (struct sockaddr *) &scm->server_addr, + scm->server_addr_size); +#endif + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "CLIENT: ERROR: connect failed (errno = %d)!\n", + errno_val); + return -1; + } + + sock_test_cfg_sync (ctrl); + printf ("CLIENT (fd %d): Control socket connected.\n", ctrl->fd); + } + while (rv < 0); + + sock_test_connect_test_sockets (ctrl->cfg.num_test_sessions); + + while (ctrl->cfg.test != VCL_TEST_TYPE_EXIT) + { + if (scm->dump_cfg) + { + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + scm->dump_cfg = 0; + } + + switch (ctrl->cfg.test) + { + case VCL_TEST_TYPE_ECHO: + echo_test_client (); + break; + + case VCL_TEST_TYPE_UNI: + case VCL_TEST_TYPE_BI: + stream_test_client (ctrl->cfg.test); + break; + + case VCL_TEST_TYPE_EXIT: + continue; + + case VCL_TEST_TYPE_NONE: + default: + break; + } + switch (post_test) + { + case VCL_TEST_TYPE_EXIT: + switch (ctrl->cfg.test) + { + case VCL_TEST_TYPE_EXIT: + case VCL_TEST_TYPE_UNI: + case VCL_TEST_TYPE_BI: + case VCL_TEST_TYPE_ECHO: + ctrl->cfg.test = VCL_TEST_TYPE_EXIT; + continue; + + case VCL_TEST_TYPE_NONE: + default: + break; + } + break; + + case VCL_TEST_TYPE_NONE: + case VCL_TEST_TYPE_ECHO: + case VCL_TEST_TYPE_UNI: + case VCL_TEST_TYPE_BI: + default: + break; + } + + memset (ctrl->txbuf, 0, ctrl->txbuf_size); + memset (ctrl->rxbuf, 0, ctrl->rxbuf_size); + + printf ("\nCLIENT: Type some characters and hit \n" + "('" VCL_TEST_TOKEN_HELP "' for help): "); + + if (fgets (ctrl->txbuf, ctrl->txbuf_size, stdin) != NULL) + { + if (strlen (ctrl->txbuf) == 1) + { + printf ("\nCLIENT: Nothing to send! Please try again...\n"); + continue; + } + ctrl->txbuf[strlen (ctrl->txbuf) - 1] = 0; // chomp the newline. + + /* Parse input for keywords */ + ctrl->cfg.test = parse_input (); + } + } + + exit_client (); +#ifdef VCL_TEST + vppcom_session_close (ctrl->fd); + vppcom_app_destroy (); + return 0; +#else + close (ctrl->fd); + return (scm->af_unix_echo_tx == scm->af_unix_echo_rx) ? 0 : -1; +#endif +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/src/plugins/hs_apps/vcl/sock_test_server.c b/src/plugins/hs_apps/vcl/sock_test_server.c new file mode 100644 index 00000000000..59dae179cd8 --- /dev/null +++ b/src/plugins/hs_apps/vcl/sock_test_server.c @@ -0,0 +1,1015 @@ +/* + * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SOCK_SERVER_USE_EPOLL 1 +#define VPPCOM_SESSION_ATTR_UNIT_TEST 0 + +#if SOCK_SERVER_USE_EPOLL +#include +#if !defined(VCL_TEST) +#include +#endif +#endif + +#ifdef VCL_TEST +#if VPPCOM_SESSION_ATTR_UNIT_TEST +#define BUFLEN sizeof (uint64_t) * 16 +uint64_t buffer[16]; +uint32_t buflen = BUFLEN; +uint32_t *flags = (uint32_t *) buffer; +#endif +#endif + +typedef struct +{ + uint8_t is_alloc; + int fd; + uint8_t *buf; + uint32_t buf_size; + vcl_test_cfg_t cfg; + vcl_test_stats_t stats; +#ifdef VCL_TEST + vppcom_endpt_t endpt; + uint8_t ip[16]; +#endif +} sock_server_conn_t; + +typedef struct +{ + uint32_t port; + uint32_t address_ip6; + uint32_t transport_udp; +} sock_server_cfg_t; + +#define SOCK_SERVER_MAX_TEST_CONN 10 +#define SOCK_SERVER_MAX_EPOLL_EVENTS 10 +typedef struct +{ + int listen_fd; + sock_server_cfg_t cfg; +#if SOCK_SERVER_USE_EPOLL + int epfd; + struct epoll_event listen_ev; + struct epoll_event wait_events[SOCK_SERVER_MAX_EPOLL_EVENTS]; +#if !defined (VCL_TEST) + int af_unix_listen_fd; + int af_unix_fd; + struct epoll_event af_unix_listen_ev; + struct sockaddr_un serveraddr; + uint32_t af_unix_xacts; +#endif +#endif + size_t num_conn; + size_t conn_pool_size; + sock_server_conn_t *conn_pool; + int nfds; + fd_set rd_fdset; + fd_set wr_fdset; + struct timeval timeout; +} sock_server_main_t; + +sock_server_main_t sock_server_main; + +#if ! SOCK_SERVER_USE_EPOLL +static inline int +get_nfds (void) +{ + sock_server_main_t *ssm = &sock_server_main; + int i, nfds; + + for (nfds = i = 0; i < FD_SETSIZE; i++) + { + if (FD_ISSET (i, &ssm->rd_fdset) || FD_ISSET (i, &ssm->wr_fdset)) + nfds = i + 1; + } + return nfds; +} + +static inline void +conn_fdset_set (sock_server_conn_t * conn, fd_set * fdset) +{ + sock_server_main_t *ssm = &sock_server_main; + + FD_SET (conn->fd, fdset); + ssm->nfds = get_nfds (); +} + +static inline void +conn_fdset_clr (sock_server_conn_t * conn, fd_set * fdset) +{ + sock_server_main_t *ssm = &sock_server_main; + + FD_CLR (conn->fd, fdset); + ssm->nfds = get_nfds (); +} +#endif + +static inline void +conn_pool_expand (size_t expand_size) +{ + sock_server_main_t *ssm = &sock_server_main; + sock_server_conn_t *conn_pool; + size_t new_size = ssm->conn_pool_size + expand_size; + int i; + + conn_pool = realloc (ssm->conn_pool, new_size * sizeof (*ssm->conn_pool)); + if (conn_pool) + { + for (i = ssm->conn_pool_size; i < new_size; i++) + { + sock_server_conn_t *conn = &conn_pool[i]; + memset (conn, 0, sizeof (*conn)); + vcl_test_cfg_init (&conn->cfg); + vcl_test_buf_alloc (&conn->cfg, 1 /* is_rxbuf */ , + &conn->buf, &conn->buf_size); + conn->cfg.txbuf_size = conn->cfg.rxbuf_size; + } + + ssm->conn_pool = conn_pool; + ssm->conn_pool_size = new_size; + } + else + { + int errno_val = errno; + perror ("ERROR in conn_pool_expand()"); + fprintf (stderr, "SERVER: ERROR: Memory allocation " + "failed (errno = %d)!\n", errno_val); + } +} + +static inline sock_server_conn_t * +conn_pool_alloc (void) +{ + sock_server_main_t *ssm = &sock_server_main; + int i; + + for (i = 0; i < ssm->conn_pool_size; i++) + { + if (!ssm->conn_pool[i].is_alloc) + { +#ifdef VCL_TEST + ssm->conn_pool[i].endpt.ip = ssm->conn_pool[i].ip; +#endif + ssm->conn_pool[i].is_alloc = 1; + return (&ssm->conn_pool[i]); + } + } + + return 0; +} + +static inline void +conn_pool_free (sock_server_conn_t * conn) +{ +#if ! SOCK_SERVER_USE_EPOLL + sock_server_main_t *ssm = &sock_server_main; + + conn_fdset_clr (conn, &ssm->rd_fdset); + conn_fdset_clr (conn, &ssm->wr_fdset); +#endif + conn->fd = 0; + conn->is_alloc = 0; +} + +static inline void +sync_config_and_reply (sock_server_conn_t * conn, vcl_test_cfg_t * rx_cfg) +{ + conn->cfg = *rx_cfg; + vcl_test_buf_alloc (&conn->cfg, 1 /* is_rxbuf */ , + &conn->buf, &conn->buf_size); + conn->cfg.txbuf_size = conn->cfg.rxbuf_size; + + if (conn->cfg.verbose) + { + printf ("\nSERVER (fd %d): Replying to cfg message!\n", conn->fd); + vcl_test_cfg_dump (&conn->cfg, 0 /* is_client */ ); + } + (void) sock_test_write (conn->fd, (uint8_t *) & conn->cfg, + sizeof (conn->cfg), NULL, conn->cfg.verbose); +} + +static void +stream_test_server_start_stop (sock_server_conn_t * conn, + vcl_test_cfg_t * rx_cfg) +{ + sock_server_main_t *ssm = &sock_server_main; + int client_fd = conn->fd; + vcl_test_t test = rx_cfg->test; + + if (rx_cfg->ctrl_handle == conn->fd) + { + int i; + clock_gettime (CLOCK_REALTIME, &conn->stats.stop); + + for (i = 0; i < ssm->conn_pool_size; i++) + { + sock_server_conn_t *tc = &ssm->conn_pool[i]; + + if (tc->cfg.ctrl_handle == conn->fd) + { + vcl_test_stats_accumulate (&conn->stats, &tc->stats); + + if (conn->cfg.verbose) + { + static char buf[64]; + + sprintf (buf, "SERVER (fd %d) RESULTS", tc->fd); + vcl_test_stats_dump (buf, &tc->stats, 1 /* show_rx */ , + test == VCL_TEST_TYPE_BI + /* show tx */ , + conn->cfg.verbose); + } + } + } + + vcl_test_stats_dump ("SERVER RESULTS", &conn->stats, 1 /* show_rx */ , + (test == VCL_TEST_TYPE_BI) /* show_tx */ , + conn->cfg.verbose); + vcl_test_cfg_dump (&conn->cfg, 0 /* is_client */ ); + if (conn->cfg.verbose) + { + printf (" sock server main\n" + VCL_TEST_SEPARATOR_STRING + " buf: %p\n" + " buf size: %u (0x%08x)\n" + VCL_TEST_SEPARATOR_STRING, + conn->buf, conn->buf_size, conn->buf_size); + } + + sync_config_and_reply (conn, rx_cfg); + printf ("\nSERVER (fd %d): %s-directional Stream Test Complete!\n" + SOCK_TEST_BANNER_STRING "\n", conn->fd, + test == VCL_TEST_TYPE_BI ? "Bi" : "Uni"); + } + else + { + printf ("\n" SOCK_TEST_BANNER_STRING + "SERVER (fd %d): %s-directional Stream Test!\n" + " Sending client the test cfg to start streaming data...\n", + client_fd, test == VCL_TEST_TYPE_BI ? "Bi" : "Uni"); + + rx_cfg->ctrl_handle = (rx_cfg->ctrl_handle == ~0) ? conn->fd : + rx_cfg->ctrl_handle; + + sync_config_and_reply (conn, rx_cfg); + + /* read the 1st chunk, record start time */ + memset (&conn->stats, 0, sizeof (conn->stats)); + clock_gettime (CLOCK_REALTIME, &conn->stats.start); + } +} + + +static inline void +stream_test_server (sock_server_conn_t * conn, int rx_bytes) +{ + int client_fd = conn->fd; + vcl_test_t test = conn->cfg.test; + + if (test == VCL_TEST_TYPE_BI) + (void) sock_test_write (client_fd, conn->buf, rx_bytes, &conn->stats, + conn->cfg.verbose); + + if (conn->stats.rx_bytes >= conn->cfg.total_bytes) + { + clock_gettime (CLOCK_REALTIME, &conn->stats.stop); + } +} + +#if SOCK_SERVER_USE_EPOLL && !defined (VCL_TEST) +static inline void +af_unix_echo (void) +{ + sock_server_main_t *ssm = &sock_server_main; + int af_unix_client_fd; + int rv; + int errno_val; + uint8_t buffer[256]; + size_t nbytes = strlen (SOCK_TEST_MIXED_EPOLL_DATA) + 1; + +#if HAVE_ACCEPT4 + af_unix_client_fd = accept4 (ssm->af_unix_listen_fd, + (struct sockaddr *) NULL, NULL, NULL); +#else + af_unix_client_fd = accept (ssm->af_unix_listen_fd, + (struct sockaddr *) NULL, NULL); +#endif + if (af_unix_client_fd < 0) + { + errno_val = errno; + perror ("ERROR in af_unix_accept()"); + fprintf (stderr, "SERVER: ERROR: accept failed " + "(errno = %d)!\n", errno_val); + return; + } + + printf ("SERVER: Got an AF_UNIX connection -- fd = %d (0x%08x)!\n", + af_unix_client_fd, af_unix_client_fd); + + memset (buffer, 0, sizeof (buffer)); + + rv = read (af_unix_client_fd, buffer, nbytes); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in af_unix_echo(): read() failed"); + fprintf (stderr, "SERVER: ERROR: read(af_unix_client_fd %d (0x%x), " + "\"%s\", nbytes %lu) failed (errno = %d)!\n", + af_unix_client_fd, af_unix_client_fd, buffer, nbytes, + errno_val); + goto done; + } + + printf ("SERVER (AF_UNIX): RX (%d bytes) - '%s'\n", rv, buffer); + + if (!strncmp (SOCK_TEST_MIXED_EPOLL_DATA, (const char *) buffer, nbytes)) + { + rv = write (af_unix_client_fd, buffer, nbytes); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in af_unix_echo(): write() failed"); + fprintf (stderr, + "SERVER: ERROR: write(af_unix_client_fd %d (0x%x), " + "\"%s\", nbytes %ld) failed (errno = %d)!\n", + af_unix_client_fd, af_unix_client_fd, buffer, nbytes, + errno_val); + goto done; + } + printf ("SERVER (AF_UNIX): TX (%d bytes) - '%s'\n", rv, buffer); + ssm->af_unix_xacts++; + } +done: + close (af_unix_client_fd); +} + +#endif + +static inline void +new_client (void) +{ + sock_server_main_t *ssm = &sock_server_main; + int client_fd; + sock_server_conn_t *conn; + + if (ssm->conn_pool_size < (ssm->num_conn + SOCK_SERVER_MAX_TEST_CONN + 1)) + conn_pool_expand (SOCK_SERVER_MAX_TEST_CONN + 1); + + conn = conn_pool_alloc (); + if (!conn) + { + fprintf (stderr, "\nSERVER: ERROR: No free connections!\n"); + return; + } + +#ifdef VCL_TEST + client_fd = vppcom_session_accept (ssm->listen_fd, &conn->endpt, 0); + if (client_fd < 0) + errno = -client_fd; +#elif HAVE_ACCEPT4 + client_fd = accept4 (ssm->listen_fd, (struct sockaddr *) NULL, NULL, NULL); +#else + client_fd = accept (ssm->listen_fd, (struct sockaddr *) NULL, NULL); +#endif + if (client_fd < 0) + { + int errno_val; + errno_val = errno; + perror ("ERROR in new_client()"); + fprintf (stderr, "SERVER: ERROR: accept failed " + "(errno = %d)!\n", errno_val); + return; + } + + printf ("SERVER: Got a connection -- fd = %d (0x%08x)!\n", + client_fd, client_fd); + + conn->fd = client_fd; + +#if ! SOCK_SERVER_USE_EPOLL + conn_fdset_set (conn, &ssm->rd_fdset); + ssm->nfds++; +#else + { + struct epoll_event ev; + int rv; + + ev.events = EPOLLIN; + ev.data.u64 = conn - ssm->conn_pool; +#ifdef VCL_TEST + rv = vppcom_epoll_ctl (ssm->epfd, EPOLL_CTL_ADD, client_fd, &ev); + if (rv) + errno = -rv; +#else + rv = epoll_ctl (ssm->epfd, EPOLL_CTL_ADD, client_fd, &ev); +#endif + if (rv < 0) + { + int errno_val; + errno_val = errno; + perror ("ERROR in new_client()"); + fprintf (stderr, "SERVER: ERROR: epoll_ctl failed (errno = %d)!\n", + errno_val); + } + else + ssm->nfds++; + } +#endif +} + +void +print_usage_and_exit (void) +{ + fprintf (stderr, + "sock_test_server [OPTIONS] \n" + " OPTIONS\n" + " -h Print this message and exit.\n" + " -6 Use IPv6\n" + " -u Use UDP transport layer\n"); + exit (1); +} + +int +main (int argc, char **argv) +{ + sock_server_main_t *ssm = &sock_server_main; + int client_fd, rv, main_rv = 0; + int tx_bytes, rx_bytes, nbytes; + sock_server_conn_t *conn; + vcl_test_cfg_t *rx_cfg; + uint32_t xtra = 0; + uint64_t xtra_bytes = 0; + struct sockaddr_storage servaddr; + int errno_val; + int c, v, i; + uint16_t port = VCL_TEST_SERVER_PORT; +#if ! SOCK_SERVER_USE_EPOLL + fd_set _rfdset, *rfdset = &_rfdset; +#endif +#ifdef VCL_TEST + vppcom_endpt_t endpt; +#else + uint32_t servaddr_size; +#if ! SOCK_SERVER_USE_EPOLL + fd_set _wfdset, *wfdset = &_wfdset; +#endif +#endif + + opterr = 0; + while ((c = getopt (argc, argv, "6D")) != -1) + switch (c) + { + case '6': + ssm->cfg.address_ip6 = 1; + break; + + case 'D': + ssm->cfg.transport_udp = 1; + break; + + case '?': + switch (optopt) + { + default: + if (isprint (optopt)) + fprintf (stderr, "SERVER: ERROR: Unknown " + "option `-%c'.\n", optopt); + else + fprintf (stderr, "SERVER: ERROR: Unknown " + "option character `\\x%x'.\n", optopt); + } + /* fall thru */ + case 'h': + default: + print_usage_and_exit (); + } + + if (argc < (optind + 1)) + { + fprintf (stderr, "SERVER: ERROR: Insufficient number of arguments!\n"); + print_usage_and_exit (); + } + + if (sscanf (argv[optind], "%d", &v) == 1) + port = (uint16_t) v; + else + { + fprintf (stderr, "SERVER: ERROR: Invalid port (%s)!\n", argv[optind]); + print_usage_and_exit (); + } + + conn_pool_expand (SOCK_SERVER_MAX_TEST_CONN + 1); + +#ifdef VCL_TEST + rv = vppcom_app_create ("vcl_test_server"); + if (rv) + { + errno = -rv; + ssm->listen_fd = -1; + } + else + { + ssm->listen_fd = vppcom_session_create (ssm->cfg.transport_udp ? + VPPCOM_PROTO_UDP : + VPPCOM_PROTO_TCP, + 0 /* is_nonblocking */ ); + } +#else + ssm->listen_fd = socket (ssm->cfg.address_ip6 ? AF_INET6 : AF_INET, + ssm->cfg.transport_udp ? SOCK_DGRAM : SOCK_STREAM, + 0); +#if SOCK_SERVER_USE_EPOLL && !defined (VCL_TEST) + unlink ((const char *) SOCK_TEST_AF_UNIX_FILENAME); + ssm->af_unix_listen_fd = socket (AF_UNIX, SOCK_STREAM, 0); + if (ssm->af_unix_listen_fd < 0) + { + errno_val = errno; + perror ("ERROR in main(): socket(AF_UNIX) failed"); + fprintf (stderr, + "SERVER: ERROR: socket(AF_UNIX, SOCK_STREAM, 0) failed " + "(errno = %d)!\n", errno_val); + return ssm->af_unix_listen_fd; + } + + memset (&ssm->serveraddr, 0, sizeof (ssm->serveraddr)); + ssm->serveraddr.sun_family = AF_UNIX; + strcpy (ssm->serveraddr.sun_path, SOCK_TEST_AF_UNIX_FILENAME); + + rv = bind (ssm->af_unix_listen_fd, (struct sockaddr *) &ssm->serveraddr, + SUN_LEN (&ssm->serveraddr)); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in main(): bind(SOCK_TEST_AF_UNIX_FILENAME) failed"); + fprintf (stderr, "SERVER: ERROR: bind() fd %d, \"%s\": " + "failed (errno = %d)!\n", ssm->af_unix_listen_fd, + SOCK_TEST_AF_UNIX_FILENAME, errno_val); + close (ssm->af_unix_listen_fd); + unlink ((const char *) SOCK_TEST_AF_UNIX_FILENAME); + return rv; + } + + rv = listen (ssm->af_unix_listen_fd, 10); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in main(): listen(AF_UNIX) failed"); + fprintf (stderr, "SERVER: ERROR: listen() fd %d, \"%s\": " + "failed (errno = %d)!\n", ssm->af_unix_listen_fd, + SOCK_TEST_AF_UNIX_FILENAME, errno_val); + close (ssm->af_unix_listen_fd); + unlink ((const char *) SOCK_TEST_AF_UNIX_FILENAME); + return rv; + } +#endif /* SOCK_SERVER_USE_EPOLL */ +#endif + if (ssm->listen_fd < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "SERVER: ERROR: socket() failed " + "(errno = %d)!\n", errno_val); + return ssm->listen_fd; + } + + memset (&servaddr, 0, sizeof (servaddr)); + + if (ssm->cfg.address_ip6) + { + struct sockaddr_in6 *server_addr = (struct sockaddr_in6 *) &servaddr; +#ifndef VCL_TEST + servaddr_size = sizeof (*server_addr); +#endif + server_addr->sin6_family = AF_INET6; + server_addr->sin6_addr = in6addr_any; + server_addr->sin6_port = htons (port); + } + else + { + struct sockaddr_in *server_addr = (struct sockaddr_in *) &servaddr; +#ifndef VCL_TEST + servaddr_size = sizeof (*server_addr); +#endif + server_addr->sin_family = AF_INET; + server_addr->sin_addr.s_addr = htonl (INADDR_ANY); + server_addr->sin_port = htons (port); + } + +#ifdef VCL_TEST + if (ssm->cfg.address_ip6) + { + struct sockaddr_in6 *server_addr = (struct sockaddr_in6 *) &servaddr; + endpt.is_ip4 = 0; + endpt.ip = (uint8_t *) & server_addr->sin6_addr; + endpt.port = (uint16_t) server_addr->sin6_port; + } + else + { + struct sockaddr_in *server_addr = (struct sockaddr_in *) &servaddr; + endpt.is_ip4 = 1; + endpt.ip = (uint8_t *) & server_addr->sin_addr; + endpt.port = (uint16_t) server_addr->sin_port; + } + + rv = vppcom_session_bind (ssm->listen_fd, &endpt); + if (rv) + { + errno = -rv; + rv = -1; + } +#else + rv = bind (ssm->listen_fd, (struct sockaddr *) &servaddr, servaddr_size); +#endif + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "SERVER: ERROR: bind failed (errno = %d)!\n", + errno_val); + return rv; + } + if (fcntl (ssm->listen_fd, F_SETFL, O_NONBLOCK) < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "SERVER: ERROR: fcntl failed (errno = %d)!\n", + errno_val); + return rv; + } + +#ifdef VCL_TEST + rv = vppcom_session_listen (ssm->listen_fd, 10); + if (rv) + { + errno = -rv; + rv = -1; + } +#else + rv = listen (ssm->listen_fd, 10); +#endif + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "SERVER: ERROR: listen failed " + "(errno = %d)!\n", errno_val); + return rv; + } + +#if ! SOCK_SERVER_USE_EPOLL + + FD_ZERO (&ssm->wr_fdset); + FD_ZERO (&ssm->rd_fdset); + + FD_SET (ssm->listen_fd, &ssm->rd_fdset); + ssm->nfds = ssm->listen_fd + 1; + +#else +#ifdef VCL_TEST + ssm->epfd = vppcom_epoll_create (); + if (ssm->epfd < 0) + errno = -ssm->epfd; +#else + ssm->epfd = epoll_create (1); +#endif + if (ssm->epfd < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "SERVER: ERROR: epoll_create failed (errno = %d)!\n", + errno_val); + return ssm->epfd; + } + + ssm->listen_ev.events = EPOLLIN; + ssm->listen_ev.data.u32 = ~0; +#ifdef VCL_TEST + rv = vppcom_epoll_ctl (ssm->epfd, EPOLL_CTL_ADD, ssm->listen_fd, + &ssm->listen_ev); + if (rv < 0) + errno = -rv; +#else + ssm->af_unix_listen_ev.events = EPOLLIN; + ssm->af_unix_listen_ev.data.u32 = SOCK_TEST_AF_UNIX_ACCEPT_DATA; + rv = epoll_ctl (ssm->epfd, EPOLL_CTL_ADD, ssm->af_unix_listen_fd, + &ssm->af_unix_listen_ev); + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in main(): mixed epoll_ctl(EPOLL_CTL_ADD)"); + fprintf (stderr, "SERVER: ERROR: mixed epoll_ctl(epfd %d (0x%x), " + "EPOLL_CTL_ADD, af_unix_listen_fd %d (0x%x), EPOLLIN) failed " + "(errno = %d)!\n", ssm->epfd, ssm->epfd, + ssm->af_unix_listen_fd, ssm->af_unix_listen_fd, errno_val); + close (ssm->af_unix_listen_fd); + unlink ((const char *) SOCK_TEST_AF_UNIX_FILENAME); + return rv; + } + + rv = epoll_ctl (ssm->epfd, EPOLL_CTL_ADD, ssm->listen_fd, &ssm->listen_ev); +#endif + if (rv < 0) + { + errno_val = errno; + perror ("ERROR in main()"); + fprintf (stderr, "SERVER: ERROR: epoll_ctl failed " + "(errno = %d)!\n", errno_val); + return rv; + } +#endif + + printf ("\nSERVER: Waiting for a client to connect on port %d...\n", port); + + while (1) + { +#if ! SOCK_SERVER_USE_EPOLL + _rfdset = ssm->rd_fdset; + +#ifdef VCL_TEST + rv = vppcom_select (ssm->nfds, (unsigned long *) rfdset, NULL, NULL, 0); +#else + { + struct timeval timeout; + timeout = ssm->timeout; + _wfdset = ssm->wr_fdset; + rv = select (ssm->nfds, rfdset, wfdset, NULL, &timeout); + } +#endif + if (rv < 0) + { + perror ("select()"); + fprintf (stderr, "\nSERVER: ERROR: select() failed -- aborting!\n"); + main_rv = -1; + goto done; + } + else if (rv == 0) + continue; + + if (FD_ISSET (ssm->listen_fd, rfdset)) + new_client (); + + for (i = 0; i < ssm->conn_pool_size; i++) + { + if (!ssm->conn_pool[i].is_alloc) + continue; + + conn = &ssm->conn_pool[i]; +#else + int num_ev; +#ifdef VCL_TEST + num_ev = vppcom_epoll_wait (ssm->epfd, ssm->wait_events, + SOCK_SERVER_MAX_EPOLL_EVENTS, 60.0); + if (num_ev < 0) + errno = -num_ev; +#else + num_ev = epoll_wait (ssm->epfd, ssm->wait_events, + SOCK_SERVER_MAX_EPOLL_EVENTS, 60000); +#endif + if (num_ev < 0) + { + perror ("epoll_wait()"); + fprintf (stderr, "\nSERVER: ERROR: epoll_wait() " + "failed -- aborting!\n"); + main_rv = -1; + goto done; + } + if (num_ev == 0) + { + fprintf (stderr, "\nSERVER: epoll_wait() timeout!\n"); + continue; + } + for (i = 0; i < num_ev; i++) + { + conn = &ssm->conn_pool[ssm->wait_events[i].data.u32]; + if (ssm->wait_events[i].events & (EPOLLHUP | EPOLLRDHUP)) + { +#ifdef VCL_TEST + vppcom_session_close (conn->fd); +#else + close (conn->fd); +#endif + continue; + } + if (ssm->wait_events[i].data.u32 == ~0) + { + new_client (); + continue; + } +#if !defined (VCL_TEST) + else if (ssm->wait_events[i].data.u32 == + SOCK_TEST_AF_UNIX_ACCEPT_DATA) + { + af_unix_echo (); + continue; + } +#endif +#endif + client_fd = conn->fd; + +#if ! SOCK_SERVER_USE_EPOLL + if (FD_ISSET (client_fd, rfdset)) +#else + if (EPOLLIN & ssm->wait_events[i].events) +#endif + { + read_again: + rx_bytes = sock_test_read (client_fd, conn->buf, + conn->buf_size, &conn->stats); + if (rx_bytes > 0) + { + rx_cfg = (vcl_test_cfg_t *) conn->buf; + if (rx_cfg->magic == VCL_TEST_CFG_CTRL_MAGIC) + { + if (rx_cfg->verbose) + { + printf ("SERVER (fd %d): Received a cfg message!\n", + client_fd); + vcl_test_cfg_dump (rx_cfg, 0 /* is_client */ ); + } + + if (rx_bytes != sizeof (*rx_cfg)) + { + printf ("SERVER (fd %d): Invalid cfg message " + "size (%d)!\n Should be %lu bytes.\n", + client_fd, rx_bytes, sizeof (*rx_cfg)); + conn->cfg.rxbuf_size = 0; + conn->cfg.num_writes = 0; + if (conn->cfg.verbose) + { + printf ("SERVER (fd %d): Replying to " + "cfg message!\n", client_fd); + vcl_test_cfg_dump (rx_cfg, 0 /* is_client */ ); + } + sock_test_write (client_fd, (uint8_t *) & conn->cfg, + sizeof (conn->cfg), NULL, + conn->cfg.verbose); + continue; + } + + switch (rx_cfg->test) + { + case VCL_TEST_TYPE_NONE: + case VCL_TEST_TYPE_ECHO: + sync_config_and_reply (conn, rx_cfg); + break; + + case VCL_TEST_TYPE_BI: + case VCL_TEST_TYPE_UNI: + stream_test_server_start_stop (conn, rx_cfg); + break; + + case VCL_TEST_TYPE_EXIT: + printf ("SERVER: Have a great day, " + "connection %d!\n", client_fd); +#ifdef VCL_TEST + vppcom_session_close (client_fd); +#else + close (client_fd); +#endif + conn_pool_free (conn); + printf ("SERVER: Closed client fd %d\n", client_fd); +#if ! SOCK_SERVER_USE_EPOLL + if (ssm->nfds == (ssm->listen_fd + 1)) +#else + ssm->nfds--; + if (!ssm->nfds) +#endif + { + printf ("SERVER: All client connections " + "closed.\n\nSERVER: " + "May the force be with you!\n\n"); + goto done; + } + break; + + default: + fprintf (stderr, + "SERVER: ERROR: Unknown test type!\n"); + vcl_test_cfg_dump (rx_cfg, 0 /* is_client */ ); + break; + } + continue; + } + + else if ((conn->cfg.test == VCL_TEST_TYPE_UNI) || + (conn->cfg.test == VCL_TEST_TYPE_BI)) + { + stream_test_server (conn, rx_bytes); + if (ioctl (conn->fd, FIONREAD)) + goto read_again; + continue; + } + + else if (isascii (conn->buf[0])) + { + // If it looks vaguely like a string, make sure it's terminated + ((char *) conn->buf)[rx_bytes < + conn->buf_size ? rx_bytes : + conn->buf_size - 1] = 0; + printf ("SERVER (fd %d): RX (%d bytes) - '%s'\n", + conn->fd, rx_bytes, conn->buf); + } + } + else // rx_bytes < 0 + { + if (errno == ECONNRESET) + { + printf ("\nSERVER: Connection reset by remote peer.\n" + " Y'all have a great day now!\n\n"); + break; + } + else + continue; + } + + if (isascii (conn->buf[0])) + { + /* If it looks vaguely like a string, + * make sure it's terminated + */ + ((char *) conn->buf)[rx_bytes < + conn->buf_size ? rx_bytes : + conn->buf_size - 1] = 0; + if (xtra) + fprintf (stderr, "SERVER: ERROR: " + "FIFO not drained in previous test!\n" + " extra chunks %u (0x%x)\n" + " extra bytes %lu (0x%lx)\n", + xtra, xtra, xtra_bytes, xtra_bytes); + + xtra = 0; + xtra_bytes = 0; + + if (conn->cfg.verbose) + printf ("SERVER (fd %d): Echoing back\n", client_fd); + + nbytes = strlen ((const char *) conn->buf) + 1; + + tx_bytes = sock_test_write (client_fd, conn->buf, + nbytes, &conn->stats, + conn->cfg.verbose); + if (tx_bytes >= 0) + printf ("SERVER (fd %d): TX (%d bytes) - '%s'\n", + conn->fd, tx_bytes, conn->buf); + } + + else // Extraneous read data from non-echo tests??? + { + xtra++; + xtra_bytes += rx_bytes; + } + } + } + } + +done: +#ifdef VCL_TEST + vppcom_session_close (ssm->listen_fd); + vppcom_app_destroy (); +#else + close (ssm->listen_fd); + +#if SOCK_SERVER_USE_EPOLL && !defined (VCL_TEST) + close (ssm->af_unix_listen_fd); + unlink ((const char *) SOCK_TEST_AF_UNIX_FILENAME); +#endif /* SOCK_SERVER_USE_EPOLL */ + +#endif + if (ssm->conn_pool) + free (ssm->conn_pool); + + return main_rv; +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/src/plugins/hs_apps/vcl/vcl_test.h b/src/plugins/hs_apps/vcl/vcl_test.h new file mode 100644 index 00000000000..ab05f7ae9cf --- /dev/null +++ b/src/plugins/hs_apps/vcl/vcl_test.h @@ -0,0 +1,538 @@ +/* + * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __vcl_test_h__ +#define __vcl_test_h__ + +#include +#include +#include +#include +#include + +#define vtfail(_fn, _rv) \ +{ \ + errno = -_rv; \ + perror ("ERROR when calling " _fn); \ + fprintf (stderr, "\nERROR: " _fn " failed (errno = %d)!\n", -_rv); \ + exit (1); \ +} + +#define vterr(_fn, _rv) \ +{ \ + errno = -_rv; \ + fprintf (stderr, "\nERROR: " _fn " failed (errno = %d)!\n", -_rv); \ +} + +#define vtwrn(_fmt, _args...) \ + fprintf (stderr, "\nERROR: " _fmt "\n", ##_args) \ + +#define vtinf(_fmt, _args...) \ + fprintf (stdout, "vt: " _fmt "\n", __wrk_index, ##_args) + +#define vt_atomic_add(_ptr, _val) \ + __atomic_fetch_add (_ptr, _val, __ATOMIC_RELEASE) + +#define VCL_TEST_TOKEN_HELP "#H" +#define VCL_TEST_TOKEN_EXIT "#X" +#define VCL_TEST_TOKEN_VERBOSE "#V" +#define VCL_TEST_TOKEN_TXBUF_SIZE "#T:" +#define VCL_TEST_TOKEN_NUM_TEST_SESS "#I:" +#define VCL_TEST_TOKEN_NUM_WRITES "#N:" +#define VCL_TEST_TOKEN_RXBUF_SIZE "#R:" +#define VCL_TEST_TOKEN_SHOW_CFG "#C" +#define VCL_TEST_TOKEN_RUN_UNI "#U" +#define VCL_TEST_TOKEN_RUN_BI "#B" + +#define VCL_TEST_SERVER_PORT 22000 +#define VCL_TEST_LOCALHOST_IPADDR "127.0.0.1" + +#define VCL_TEST_CFG_CTRL_MAGIC 0xfeedface +#define VCL_TEST_CFG_NUM_WRITES_DEF 1000000 +#define VCL_TEST_CFG_TXBUF_SIZE_DEF 8192 +#define VCL_TEST_CFG_RXBUF_SIZE_DEF (64*VCL_TEST_CFG_TXBUF_SIZE_DEF) +#define VCL_TEST_CFG_BUF_SIZE_MIN 128 +#define VCL_TEST_CFG_MAX_TEST_SESS 32 +#define VCL_TEST_CFG_MAX_EPOLL_EVENTS 16 + +#define VCL_TEST_DELAY_DISCONNECT 1 +#define VCL_TEST_SEPARATOR_STRING \ + " -----------------------------\n" +typedef enum +{ + VCL_TEST_TYPE_NONE, + VCL_TEST_TYPE_ECHO, + VCL_TEST_TYPE_UNI, + VCL_TEST_TYPE_BI, + VCL_TEST_TYPE_EXIT, +} vcl_test_t; + +typedef struct __attribute__ ((packed)) +{ + uint32_t magic; + uint32_t seq_num; + uint32_t test; + uint32_t ctrl_handle; + uint32_t num_test_sessions; + uint32_t verbose; + uint32_t address_ip6; + uint32_t transport_udp; + uint32_t transport_tls; + uint64_t rxbuf_size; + uint64_t txbuf_size; + uint64_t num_writes; + uint64_t total_bytes; +} vcl_test_cfg_t; + +typedef struct +{ + uint64_t rx_xacts; + uint64_t rx_bytes; + uint32_t rx_eagain; + uint32_t rx_incomp; + uint64_t tx_xacts; + uint64_t tx_bytes; + uint32_t tx_eagain; + uint32_t tx_incomp; + struct timespec start; + struct timespec stop; +} vcl_test_stats_t; + +typedef struct +{ + int fd; + uint32_t txbuf_size; + char *txbuf; + uint32_t rxbuf_size; + char *rxbuf; + vcl_test_cfg_t cfg; + vcl_test_stats_t stats; +} vcl_test_session_t; + + +/* + * TLS server cert and keys to be used for testing only + */ +char vcl_test_crt_rsa[] = + "-----BEGIN CERTIFICATE-----\r\n" + "MIID5zCCAs+gAwIBAgIJALeMYCEHrTtJMA0GCSqGSIb3DQEBCwUAMIGJMQswCQYD\r\n" + "VQQGEwJVUzELMAkGA1UECAwCQ0ExETAPBgNVBAcMCFNhbiBKb3NlMQ4wDAYDVQQK\r\n" + "DAVDaXNjbzEOMAwGA1UECwwFZmQuaW8xFjAUBgNVBAMMDXRlc3R0bHMuZmQuaW8x\r\n" + "IjAgBgkqhkiG9w0BCQEWE3ZwcC1kZXZAbGlzdHMuZmQuaW8wHhcNMTgwMzA1MjEx\r\n" + "NTEyWhcNMjgwMzAyMjExNTEyWjCBiTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNB\r\n" + "MREwDwYDVQQHDAhTYW4gSm9zZTEOMAwGA1UECgwFQ2lzY28xDjAMBgNVBAsMBWZk\r\n" + "LmlvMRYwFAYDVQQDDA10ZXN0dGxzLmZkLmlvMSIwIAYJKoZIhvcNAQkBFhN2cHAt\r\n" + "ZGV2QGxpc3RzLmZkLmlvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\r\n" + "4C1k8a1DuStgggqT4o09fP9sJ2dC54bxhS/Xk2VEfaIZ222WSo4X/syRVfVy9Yah\r\n" + "cpI1zJ/RDxaZSFhgA+nPZBrFMsrULkrdAOpOVj8eDEp9JuWdO2ODSoFnCvLxcYWB\r\n" + "Yc5kHryJpEaGJl1sFQSesnzMFty/59ta0stk0Fp8r5NhIjWvSovGzPo6Bhz+VS2c\r\n" + "ebIZh4x1t2hHaFcgm0qJoJ6DceReWCW8w+yOVovTolGGq+bpb2Hn7MnRSZ2K2NdL\r\n" + "+aLXpkZbS/AODP1FF2vTO1mYL290LO7/51vJmPXNKSDYMy5EvILr5/VqtjsFCwRL\r\n" + "Q4jcM/+GeHSAFWx4qIv0BwIDAQABo1AwTjAdBgNVHQ4EFgQUWa1SOB37xmT53tZQ\r\n" + "aXuLLhRI7U8wHwYDVR0jBBgwFoAUWa1SOB37xmT53tZQaXuLLhRI7U8wDAYDVR0T\r\n" + "BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAoUht13W4ya27NVzQuCMvqPWL3VM4\r\n" + "3xbPFk02FaGz/WupPu276zGlzJAZrbuDcQowwwU1Ni1Yygxl96s1c2M5rHDTrOKG\r\n" + "rK0hbkSFBo+i6I8u4HiiQ4rYmG0Hv6+sXn3of0HsbtDPGgWZoipPWDljPYEURu3e\r\n" + "3HRe/Dtsj9CakBoSDzs8ndWaBR+f4sM9Tk1cjD46Gq2T/qpSPXqKxEUXlzhdCAn4\r\n" + "twub17Bq2kykHpppCwPg5M+v30tHG/R2Go15MeFWbEJthFk3TZMjKL7UFs7fH+x2\r\n" + "wSonXb++jY+KmCb93C+soABBizE57g/KmiR2IxQ/LMjDik01RSUIaM0lLA==\r\n" + "-----END CERTIFICATE-----\r\n"; +uint32_t vcl_test_crt_rsa_len = sizeof (vcl_test_crt_rsa); + +char vcl_test_key_rsa[] = + "-----BEGIN PRIVATE KEY-----\r\n" + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDgLWTxrUO5K2CC\r\n" + "CpPijT18/2wnZ0LnhvGFL9eTZUR9ohnbbZZKjhf+zJFV9XL1hqFykjXMn9EPFplI\r\n" + "WGAD6c9kGsUyytQuSt0A6k5WPx4MSn0m5Z07Y4NKgWcK8vFxhYFhzmQevImkRoYm\r\n" + "XWwVBJ6yfMwW3L/n21rSy2TQWnyvk2EiNa9Ki8bM+joGHP5VLZx5shmHjHW3aEdo\r\n" + "VyCbSomgnoNx5F5YJbzD7I5Wi9OiUYar5ulvYefsydFJnYrY10v5otemRltL8A4M\r\n" + "/UUXa9M7WZgvb3Qs7v/nW8mY9c0pINgzLkS8guvn9Wq2OwULBEtDiNwz/4Z4dIAV\r\n" + "bHioi/QHAgMBAAECggEBAMzGipP8+oT166U+NlJXRFifFVN1DvdhG9PWnOxGL+c3\r\n" + "ILmBBC08WQzmHshPemBvR6DZkA1H23cV5JTiLWrFtC00CvhXsLRMrE5+uWotI6yE\r\n" + "iofybMroHvD6/X5R510UX9hQ6MHu5ShLR5VZ9zXHz5MpTmB/60jG5dLx+jgcwBK8\r\n" + "LuGv2YB/WCUwT9QJ3YU2eaingnXtz/MrFbkbltrqlnBdlD+kTtw6Yac9y1XuuQXc\r\n" + "BPeulLNDuPolJVWbUvDBZrpt2dXTgz8ws1sv+wCNE0xwQJsqW4Nx3QkpibUL9RUr\r\n" + "CVbKlNfa9lopT6nGKlgX69R/uH35yh9AOsfasro6w0ECgYEA82UJ8u/+ORah+0sF\r\n" + "Q0FfW5MTdi7OAUHOz16pUsGlaEv0ERrjZxmAkHA/VRwpvDBpx4alCv0Hc39PFLIk\r\n" + "nhSsM2BEuBkTAs6/GaoNAiBtQVE/hN7awNRWVmlieS0go3Y3dzaE9IUMyj8sPOFT\r\n" + "5JdJ6BM69PHKCkY3dKdnnfpFEuECgYEA68mRpteunF1mdZgXs+WrN+uLlRrQR20F\r\n" + "ZyMYiUCH2Dtn26EzA2moy7FipIIrQcX/j+KhYNGM3e7MU4LymIO29E18mn8JODnH\r\n" + "sQOXzBTsf8A4yIVMkcuQD3bfb0JiUGYUPOidTp2N7IJA7+6Yc3vQOyb74lnKnJoO\r\n" + "gougPT2wS+cCgYAn7muzb6xFsXDhyW0Tm6YJYBfRS9yAWEuVufINobeBZPSl2cN1\r\n" + "Jrnw+HlrfTNbrJWuJmjtZJXUXQ6cVp2rUbjutNyRV4vG6iRwEXYQ40EJdkr1gZpi\r\n" + "CHQhuShuuPih2MNAy7EEbM+sXrDjTBR3bFqzuHPzu7dp+BshCFX3lRfAAQKBgGQt\r\n" + "K5i7IhCFDjb/+3IPLgOAK7mZvsvZ4eXD33TQ2eZgtut1PXtBtNl17/b85uv293Fm\r\n" + "VDISVcsk3eLNS8zIiT6afUoWlxAwXEs0v5WRfjl4radkGvgGiJpJYvyeM67877RB\r\n" + "EDSKc/X8ESLfOB44iGvZUEMG6zJFscx9DgN25iQZAoGAbyd+JEWwdVH9/K3IH1t2\r\n" + "PBkZX17kNWv+iVM1WyFjbe++vfKZCrOJiyiqhDeEqgrP3AuNMlaaduC3VRC3G5oV\r\n" + "Mj1tlhDWQ/qhvKdCKNdIVQYDE75nw+FRWV8yYkHAnXYW3tNoweDIwixE0hkPR1bc\r\n" + "oEjPLVNtx8SOj/M4rhaPT3I=\r\n" "-----END PRIVATE KEY-----\r\n"; +uint32_t vcl_test_key_rsa_len = sizeof (vcl_test_key_rsa); + +static inline void +vcl_test_stats_accumulate (vcl_test_stats_t * accum, vcl_test_stats_t * incr) +{ + accum->rx_xacts += incr->rx_xacts; + accum->rx_bytes += incr->rx_bytes; + accum->rx_eagain += incr->rx_eagain; + accum->rx_incomp += incr->rx_incomp; + accum->tx_xacts += incr->tx_xacts; + accum->tx_bytes += incr->tx_bytes; + accum->tx_eagain += incr->tx_eagain; + accum->tx_incomp += incr->tx_incomp; +} + +static inline void +vcl_test_cfg_init (vcl_test_cfg_t * cfg) +{ + cfg->magic = VCL_TEST_CFG_CTRL_MAGIC; + cfg->test = VCL_TEST_TYPE_NONE; + cfg->ctrl_handle = ~0; + cfg->num_test_sessions = 1; + cfg->verbose = 0; + cfg->rxbuf_size = VCL_TEST_CFG_RXBUF_SIZE_DEF; + cfg->num_writes = VCL_TEST_CFG_NUM_WRITES_DEF; + cfg->txbuf_size = VCL_TEST_CFG_TXBUF_SIZE_DEF; + cfg->total_bytes = cfg->num_writes * cfg->txbuf_size; +} + +static inline int +vcl_test_cfg_verify (vcl_test_cfg_t * cfg, vcl_test_cfg_t * valid_cfg) +{ + /* Note: txbuf & rxbuf on server are the same buffer, + * so txbuf_size is not included in this check. + */ + return ((cfg->magic == valid_cfg->magic) + && (cfg->test == valid_cfg->test) + && (cfg->verbose == valid_cfg->verbose) + && (cfg->rxbuf_size == valid_cfg->rxbuf_size) + && (cfg->num_writes == valid_cfg->num_writes) + && (cfg->total_bytes == valid_cfg->total_bytes)); +} + +static inline void +vcl_test_buf_alloc (vcl_test_cfg_t * cfg, uint8_t is_rxbuf, uint8_t ** buf, + uint32_t * bufsize) +{ + uint32_t alloc_size = is_rxbuf ? cfg->rxbuf_size : cfg->txbuf_size; + uint8_t *lb = realloc (*buf, (size_t) alloc_size); + + if (lb) + { + if (is_rxbuf) + cfg->rxbuf_size = *bufsize = alloc_size; + else + cfg->txbuf_size = *bufsize = alloc_size; + + *buf = lb; + } + else + { + vtwrn ("realloc failed. using buffer size %d instead of %u", + *bufsize, alloc_size); + } +} + +static inline void +vcl_test_session_buf_alloc (vcl_test_session_t * socket) +{ + socket->rxbuf_size = socket->cfg.rxbuf_size; + socket->txbuf_size = socket->cfg.txbuf_size; + vcl_test_buf_alloc (&socket->cfg, 0 /* is_rxbuf */ , + (uint8_t **) & socket->txbuf, &socket->txbuf_size); + vcl_test_buf_alloc (&socket->cfg, 1 /* is_rxbuf */ , + (uint8_t **) & socket->rxbuf, &socket->rxbuf_size); +} + +static inline char * +vcl_test_type_str (vcl_test_t t) +{ + switch (t) + { + case VCL_TEST_TYPE_NONE: + return "NONE"; + + case VCL_TEST_TYPE_ECHO: + return "ECHO"; + + case VCL_TEST_TYPE_UNI: + return "UNI"; + + case VCL_TEST_TYPE_BI: + return "BI"; + + case VCL_TEST_TYPE_EXIT: + return "EXIT"; + + default: + return "Unknown"; + } +} + +static inline void +vcl_test_cfg_dump (vcl_test_cfg_t * cfg, uint8_t is_client) +{ + char *spc = " "; + + printf (" test config (%p):\n" + VCL_TEST_SEPARATOR_STRING + " magic: 0x%08x\n" + " seq_num: 0x%08x\n" + "%-5s test: %s (%d)\n" + " ctrl handle: %d (0x%x)\n" + "%-5s num test sockets: %u (0x%08x)\n" + "%-5s verbose: %s (%d)\n" + "%-5s rxbuf size: %lu (0x%08lx)\n" + "%-5s txbuf size: %lu (0x%08lx)\n" + "%-5s num writes: %lu (0x%08lx)\n" + " client tx bytes: %lu (0x%08lx)\n" + VCL_TEST_SEPARATOR_STRING, + (void *) cfg, cfg->magic, cfg->seq_num, + is_client && (cfg->test == VCL_TEST_TYPE_UNI) ? + "'" VCL_TEST_TOKEN_RUN_UNI "'" : + is_client && (cfg->test == VCL_TEST_TYPE_BI) ? + "'" VCL_TEST_TOKEN_RUN_BI "'" : spc, + vcl_test_type_str (cfg->test), cfg->test, + cfg->ctrl_handle, cfg->ctrl_handle, + is_client ? "'" VCL_TEST_TOKEN_NUM_TEST_SESS "'" : spc, + cfg->num_test_sessions, cfg->num_test_sessions, + is_client ? "'" VCL_TEST_TOKEN_VERBOSE "'" : spc, + cfg->verbose ? "on" : "off", cfg->verbose, + is_client ? "'" VCL_TEST_TOKEN_RXBUF_SIZE "'" : spc, + cfg->rxbuf_size, cfg->rxbuf_size, + is_client ? "'" VCL_TEST_TOKEN_TXBUF_SIZE "'" : spc, + cfg->txbuf_size, cfg->txbuf_size, + is_client ? "'" VCL_TEST_TOKEN_NUM_WRITES "'" : spc, + cfg->num_writes, cfg->num_writes, + cfg->total_bytes, cfg->total_bytes); +} + +static inline void +vcl_test_stats_dump (char *header, vcl_test_stats_t * stats, + uint8_t show_rx, uint8_t show_tx, uint8_t verbose) +{ + struct timespec diff; + double duration, rate; + uint64_t total_bytes; + + if ((stats->stop.tv_nsec - stats->start.tv_nsec) < 0) + { + diff.tv_sec = stats->stop.tv_sec - stats->start.tv_sec - 1; + diff.tv_nsec = stats->stop.tv_nsec - stats->start.tv_nsec + 1e9; + } + else + { + diff.tv_sec = stats->stop.tv_sec - stats->start.tv_sec; + diff.tv_nsec = stats->stop.tv_nsec - stats->start.tv_nsec; + } + duration = (double) diff.tv_sec + (1e-9 * diff.tv_nsec); + + total_bytes = stats->tx_bytes + stats->rx_bytes; + rate = (double) total_bytes *8 / duration / 1e9; + printf ("\n%s: Streamed %lu bytes\n" + " in %lf seconds (%lf Gbps %s-duplex)!\n", + header, total_bytes, duration, rate, + (show_rx && show_tx) ? "full" : "half"); + + if (show_tx) + { + printf (VCL_TEST_SEPARATOR_STRING + " tx stats (0x%p):\n" + VCL_TEST_SEPARATOR_STRING + " writes: %lu (0x%08lx)\n" + " tx bytes: %lu (0x%08lx)\n" + " tx eagain: %u (0x%08x)\n" + " tx incomplete: %u (0x%08x)\n", + (void *) stats, stats->tx_xacts, stats->tx_xacts, + stats->tx_bytes, stats->tx_bytes, + stats->tx_eagain, stats->tx_eagain, + stats->tx_incomp, stats->tx_incomp); + } + if (show_rx) + { + printf (VCL_TEST_SEPARATOR_STRING + " rx stats (0x%p):\n" + VCL_TEST_SEPARATOR_STRING + " reads: %lu (0x%08lx)\n" + " rx bytes: %lu (0x%08lx)\n" + " rx eagain: %u (0x%08x)\n" + " rx incomplete: %u (0x%08x)\n", + (void *) stats, stats->rx_xacts, stats->rx_xacts, + stats->rx_bytes, stats->rx_bytes, + stats->rx_eagain, stats->rx_eagain, + stats->rx_incomp, stats->rx_incomp); + } + if (verbose) + printf (" start.tv_sec: %ld\n" + " start.tv_nsec: %ld\n" + " stop.tv_sec: %ld\n" + " stop.tv_nsec: %ld\n", + stats->start.tv_sec, stats->start.tv_nsec, + stats->stop.tv_sec, stats->stop.tv_nsec); + + printf (VCL_TEST_SEPARATOR_STRING); +} + +static inline int +vcl_comp_tspec (struct timespec *a, struct timespec *b) +{ + if (a->tv_sec < b->tv_sec) + return -1; + else if (a->tv_sec > b->tv_sec) + return 1; + else if (a->tv_nsec < b->tv_nsec) + return -1; + else if (a->tv_nsec > b->tv_nsec) + return 1; + else + return 0; +} + +static inline int +vcl_test_read (int fd, uint8_t * buf, uint32_t nbytes, + vcl_test_stats_t * stats) +{ + int rx_bytes; + + do + { + if (stats) + stats->rx_xacts++; + rx_bytes = vppcom_session_read (fd, buf, nbytes); + + if (rx_bytes < 0) + { + errno = -rx_bytes; + rx_bytes = -1; + } + if (stats) + { + if ((rx_bytes == 0) || + ((rx_bytes < 0) + && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))) + stats->rx_eagain++; + else if (rx_bytes < nbytes) + stats->rx_incomp++; + } + } + while ((rx_bytes == 0) || + ((rx_bytes < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))); + + if (rx_bytes < 0) + { + vterr ("vppcom_session_read()", -errno); + } + else if (stats) + stats->rx_bytes += rx_bytes; + + return (rx_bytes); +} + +static inline int +vcl_test_read_ds (int fd, vppcom_data_segments_t ds, vcl_test_stats_t * stats) +{ + int rx_bytes; + + do + { + if (stats) + stats->rx_xacts++; + rx_bytes = vppcom_session_read_segments (fd, ds); + + if (rx_bytes < 0) + { + errno = -rx_bytes; + rx_bytes = -1; + } + if (stats) + { + if ((rx_bytes == 0) || + ((rx_bytes < 0) + && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))) + stats->rx_eagain++; + } + } + while ((rx_bytes == 0) || + ((rx_bytes < 0) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))); + + if (rx_bytes < 0) + { + vterr ("vppcom_session_read()", -errno); + } + else if (stats) + stats->rx_bytes += rx_bytes; + + return (rx_bytes); +} + +static inline int +vcl_test_write (int fd, uint8_t * buf, uint32_t nbytes, + vcl_test_stats_t * stats, uint32_t verbose) +{ + int tx_bytes = 0, nbytes_left = nbytes, rv; + + do + { + if (stats) + stats->tx_xacts++; + rv = vppcom_session_write (fd, buf, nbytes_left); + if (rv < 0) + { + errno = -rv; + rv = -1; + } + if (rv < 0) + { + if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) + { + if (stats) + stats->tx_eagain++; + break; + } + else + break; + } + tx_bytes += rv; + + if (tx_bytes != nbytes) + { + nbytes_left = nbytes_left - rv; + buf += rv; + if (stats) + stats->tx_incomp++; + } + + } + while (tx_bytes != nbytes); + + if (tx_bytes < 0) + { + vterr ("vpcom_session_write", -errno); + } + else if (stats) + stats->tx_bytes += tx_bytes; + + return (tx_bytes); +} + +#endif /* __vcl_test_h__ */ + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/src/plugins/hs_apps/vcl/vcl_test_client.c b/src/plugins/hs_apps/vcl/vcl_test_client.c new file mode 100644 index 00000000000..1ead146aef5 --- /dev/null +++ b/src/plugins/hs_apps/vcl/vcl_test_client.c @@ -0,0 +1,1097 @@ +/* + * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct +{ + vcl_test_session_t *sessions; + uint32_t n_sessions; + uint32_t wrk_index; + fd_set wr_fdset; + fd_set rd_fdset; + int max_fd_index; + pthread_t thread_handle; + vcl_test_cfg_t cfg; +} vcl_test_client_worker_t; + +typedef struct +{ + vcl_test_client_worker_t *workers; + vppcom_endpt_t server_endpt; + uint32_t cfg_seq_num; + vcl_test_session_t ctrl_session; + vcl_test_session_t *sessions; + uint8_t dump_cfg; + vcl_test_t post_test; + uint32_t proto; + uint32_t n_workers; + volatile int active_workers; + struct sockaddr_storage server_addr; +} vcl_test_client_main_t; + +static __thread int __wrk_index = 0; + +vcl_test_client_main_t vcl_client_main; + +#define vtc_min(a, b) (a < b ? a : b) +#define vtc_max(a, b) (a > b ? a : b) + +static int +vtc_cfg_sync (vcl_test_session_t * ts) +{ + vcl_test_cfg_t *rx_cfg = (vcl_test_cfg_t *) ts->rxbuf; + int rx_bytes, tx_bytes; + + vt_atomic_add (&ts->cfg.seq_num, 1); + if (ts->cfg.verbose) + { + vtinf ("(fd %d): Sending config to server.", ts->fd); + vcl_test_cfg_dump (&ts->cfg, 1 /* is_client */ ); + } + tx_bytes = vcl_test_write (ts->fd, (uint8_t *) & ts->cfg, + sizeof (ts->cfg), NULL, ts->cfg.verbose); + if (tx_bytes < 0) + { + vtwrn ("(fd %d): write test cfg failed (%d)!", ts->fd, tx_bytes); + return tx_bytes; + } + + rx_bytes = vcl_test_read (ts->fd, (uint8_t *) ts->rxbuf, + sizeof (vcl_test_cfg_t), NULL); + if (rx_bytes < 0) + return rx_bytes; + + if (rx_cfg->magic != VCL_TEST_CFG_CTRL_MAGIC) + { + vtwrn ("(fd %d): Bad server reply cfg -- aborting!", ts->fd); + return -1; + } + if ((rx_bytes != sizeof (vcl_test_cfg_t)) + || !vcl_test_cfg_verify (rx_cfg, &ts->cfg)) + { + vtwrn ("(fd %d): Invalid config received from server!", ts->fd); + if (rx_bytes != sizeof (vcl_test_cfg_t)) + { + vtinf ("\tRx bytes %d != cfg size %lu", rx_bytes, + sizeof (vcl_test_cfg_t)); + } + else + { + vcl_test_cfg_dump (rx_cfg, 1 /* is_client */ ); + vtinf ("(fd %d): Valid config sent to server.", ts->fd); + vcl_test_cfg_dump (&ts->cfg, 1 /* is_client */ ); + } + return -1; + } + if (ts->cfg.verbose) + { + vtinf ("(fd %d): Got config back from server.", ts->fd); + vcl_test_cfg_dump (rx_cfg, 1 /* is_client */ ); + } + + return 0; +} + +static int +vtc_connect_test_sessions (vcl_test_client_worker_t * wrk) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ts; + uint32_t n_test_sessions; + int i, rv; + + n_test_sessions = wrk->cfg.num_test_sessions; + if (n_test_sessions < 1) + { + errno = EINVAL; + return -1; + } + + if (wrk->n_sessions >= n_test_sessions) + goto done; + + if (wrk->n_sessions) + wrk->sessions = realloc (wrk->sessions, + n_test_sessions * sizeof (vcl_test_session_t)); + else + wrk->sessions = calloc (n_test_sessions, sizeof (vcl_test_session_t)); + + if (!wrk->sessions) + { + vterr ("failed to alloc sessions", -errno); + return errno; + } + + for (i = 0; i < n_test_sessions; i++) + { + ts = &wrk->sessions[i]; + ts->fd = vppcom_session_create (vcm->proto, 1 /* is_nonblocking */ ); + if (ts->fd < 0) + { + vterr ("vppcom_session_create()", ts->fd); + return ts->fd; + } + + rv = vppcom_session_connect (ts->fd, &vcm->server_endpt); + if (rv < 0) + { + vterr ("vppcom_session_connect()", rv); + return rv; + } + vtinf ("Test session %d (fd %d) connected.", i, ts->fd); + } + wrk->n_sessions = n_test_sessions; + +done: + vtinf ("All test sessions (%d) connected!", n_test_sessions); + return 0; +} + +static int +vtc_worker_test_setup (vcl_test_client_worker_t * wrk) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + vcl_test_cfg_t *cfg = &wrk->cfg; + vcl_test_session_t *ts; + uint32_t sidx; + int i, j; + + FD_ZERO (&wrk->wr_fdset); + FD_ZERO (&wrk->rd_fdset); + + for (i = 0; i < cfg->num_test_sessions; i++) + { + ts = &wrk->sessions[i]; + ts->cfg = wrk->cfg; + vcl_test_session_buf_alloc (ts); + + switch (cfg->test) + { + case VCL_TEST_TYPE_ECHO: + memcpy (ts->txbuf, ctrl->txbuf, cfg->total_bytes); + break; + case VCL_TEST_TYPE_UNI: + case VCL_TEST_TYPE_BI: + for (j = 0; j < ts->txbuf_size; j++) + ts->txbuf[j] = j & 0xff; + break; + } + + FD_SET (vppcom_session_index (ts->fd), &wrk->wr_fdset); + FD_SET (vppcom_session_index (ts->fd), &wrk->rd_fdset); + sidx = vppcom_session_index (ts->fd); + wrk->max_fd_index = vtc_max (sidx, wrk->max_fd_index); + } + wrk->max_fd_index += 1; + + return 0; +} + +static int +vtc_worker_init (vcl_test_client_worker_t * wrk) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_cfg_t *cfg = &wrk->cfg; + vcl_test_session_t *ts; + uint32_t n; + int rv; + + __wrk_index = wrk->wrk_index; + + vtinf ("Initializing worker %u ...", wrk->wrk_index); + + if (wrk->wrk_index) + { + if (vppcom_worker_register ()) + { + vtwrn ("failed to register worker"); + return -1; + } + vt_atomic_add (&vcm->active_workers, 1); + } + rv = vtc_connect_test_sessions (wrk); + if (rv) + { + vterr ("vtc_connect_test_sessions ()", rv); + return rv; + } + + if (vtc_worker_test_setup (wrk)) + return -1; + + vtinf ("Sending config to server on all sessions ..."); + + for (n = 0; n < cfg->num_test_sessions; n++) + { + ts = &wrk->sessions[n]; + if (vtc_cfg_sync (ts)) + return -1; + memset (&ts->stats, 0, sizeof (ts->stats)); + } + + return 0; +} + +static int stats_lock = 0; + +static void +vtc_accumulate_stats (vcl_test_client_worker_t * wrk, + vcl_test_session_t * ctrl) +{ + vcl_test_session_t *ts; + static char buf[64]; + int i, show_rx = 0; + + while (__sync_lock_test_and_set (&stats_lock, 1)) + ; + + if (ctrl->cfg.test == VCL_TEST_TYPE_BI + || ctrl->cfg.test == VCL_TEST_TYPE_ECHO) + show_rx = 1; + + for (i = 0; i < wrk->cfg.num_test_sessions; i++) + { + ts = &wrk->sessions[i]; + ts->stats.start = ctrl->stats.start; + + if (ctrl->cfg.verbose > 1) + { + sprintf (buf, "CLIENT (fd %d) RESULTS", ts->fd); + vcl_test_stats_dump (buf, &ts->stats, show_rx, 1 /* show tx */ , + ctrl->cfg.verbose); + } + + vcl_test_stats_accumulate (&ctrl->stats, &ts->stats); + if (vcl_comp_tspec (&ctrl->stats.stop, &ts->stats.stop) < 0) + ctrl->stats.stop = ts->stats.stop; + } + + __sync_lock_release (&stats_lock); +} + +static void +vtc_worker_sessions_exit (vcl_test_client_worker_t * wrk) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + vcl_test_session_t *ts; + int i, verbose = ctrl->cfg.verbose; + + for (i = 0; i < wrk->cfg.num_test_sessions; i++) + { + ts = &wrk->sessions[i]; + ts->cfg.test = VCL_TEST_TYPE_EXIT; + + if (verbose) + { + vtinf ("(fd %d): Sending exit cfg to server...", ts->fd); + vcl_test_cfg_dump (&ts->cfg, 1 /* is_client */ ); + } + (void) vcl_test_write (ts->fd, (uint8_t *) & ts->cfg, + sizeof (ts->cfg), &ts->stats, verbose); + } + wrk->n_sessions = 0; +} + +static void * +vtc_worker_loop (void *arg) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + vcl_test_client_worker_t *wrk = arg; + uint32_t n_active_sessions, n_bytes; + fd_set _wfdset, *wfdset = &_wfdset; + fd_set _rfdset, *rfdset = &_rfdset; + vcl_test_session_t *ts; + int i, rv, check_rx = 0; + + rv = vtc_worker_init (wrk); + if (rv) + { + vterr ("vtc_worker_init()", rv); + return 0; + } + + vtinf ("Starting test ..."); + + if (wrk->wrk_index == 0) + clock_gettime (CLOCK_REALTIME, &ctrl->stats.start); + + check_rx = wrk->cfg.test != VCL_TEST_TYPE_UNI; + n_active_sessions = wrk->cfg.num_test_sessions; + while (n_active_sessions) + { + _wfdset = wrk->wr_fdset; + _rfdset = wrk->rd_fdset; + + rv = vppcom_select (wrk->max_fd_index, (unsigned long *) rfdset, + (unsigned long *) wfdset, NULL, 0); + if (rv < 0) + { + vterr ("vppcom_select()", rv); + goto exit; + } + else if (rv == 0) + continue; + + for (i = 0; i < wrk->cfg.num_test_sessions; i++) + { + ts = &wrk->sessions[i]; + if (!((ts->stats.stop.tv_sec == 0) && + (ts->stats.stop.tv_nsec == 0))) + continue; + + if (FD_ISSET (vppcom_session_index (ts->fd), rfdset) + && ts->stats.rx_bytes < ts->cfg.total_bytes) + { + (void) vcl_test_read (ts->fd, (uint8_t *) ts->rxbuf, + ts->rxbuf_size, &ts->stats); + } + + if (FD_ISSET (vppcom_session_index (ts->fd), wfdset) + && ts->stats.tx_bytes < ts->cfg.total_bytes) + { + n_bytes = ts->cfg.txbuf_size; + if (ts->cfg.test == VCL_TEST_TYPE_ECHO) + n_bytes = strlen (ctrl->txbuf) + 1; + rv = vcl_test_write (ts->fd, (uint8_t *) ts->txbuf, + n_bytes, &ts->stats, ts->cfg.verbose); + if (rv < 0) + { + vtwrn ("vppcom_test_write (%d) failed -- aborting test", + ts->fd); + goto exit; + } + } + + if ((!check_rx && ts->stats.tx_bytes >= ts->cfg.total_bytes) + || (check_rx && ts->stats.rx_bytes >= ts->cfg.total_bytes)) + { + clock_gettime (CLOCK_REALTIME, &ts->stats.stop); + n_active_sessions--; + } + } + } +exit: + vtinf ("Worker %d done ...", wrk->wrk_index); + if (wrk->cfg.test != VCL_TEST_TYPE_ECHO) + vtc_accumulate_stats (wrk, ctrl); + sleep (VCL_TEST_DELAY_DISCONNECT); + vtc_worker_sessions_exit (wrk); + if (wrk->wrk_index) + vt_atomic_add (&vcm->active_workers, -1); + return 0; +} + +static void +vtc_print_stats (vcl_test_session_t * ctrl) +{ + int is_echo = ctrl->cfg.test == VCL_TEST_TYPE_ECHO; + int show_rx = 0; + char buf[64]; + + if (ctrl->cfg.test == VCL_TEST_TYPE_BI + || ctrl->cfg.test == VCL_TEST_TYPE_ECHO) + show_rx = 1; + + vcl_test_stats_dump ("CLIENT RESULTS", &ctrl->stats, + show_rx, 1 /* show tx */ , + ctrl->cfg.verbose); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + + if (ctrl->cfg.verbose) + { + vtinf (" ctrl session info\n" + VCL_TEST_SEPARATOR_STRING + " fd: %d (0x%08x)\n" + " rxbuf: %p\n" + " rxbuf size: %u (0x%08x)\n" + " txbuf: %p\n" + " txbuf size: %u (0x%08x)\n" + VCL_TEST_SEPARATOR_STRING, + ctrl->fd, (uint32_t) ctrl->fd, + ctrl->rxbuf, ctrl->rxbuf_size, ctrl->rxbuf_size, + ctrl->txbuf, ctrl->txbuf_size, ctrl->txbuf_size); + } + + if (is_echo) + sprintf (buf, "Echo"); + else + sprintf (buf, "%s-directional Stream", + ctrl->cfg.test == VCL_TEST_TYPE_BI ? "Bi" : "Uni"); +} + +static void +vtc_echo_client (vcl_test_client_main_t * vcm) +{ + vcl_test_client_worker_t *wrk; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + vcl_test_cfg_t *cfg = &ctrl->cfg; + + cfg->total_bytes = strlen (ctrl->txbuf) + 1; + memset (&ctrl->stats, 0, sizeof (ctrl->stats)); + + /* Echo works with only one worker */ + wrk = vcm->workers; + wrk->wrk_index = 0; + wrk->cfg = *cfg; + + vtc_worker_loop (wrk); + + /* Not relevant for echo test + clock_gettime (CLOCK_REALTIME, &ctrl->stats.stop); + vtc_accumulate_stats (wrk, ctrl); + vtc_print_stats (ctrl); + */ +} + +static void +vtc_stream_client (vcl_test_client_main_t * vcm) +{ + vcl_test_session_t *ctrl = &vcm->ctrl_session; + vcl_test_cfg_t *cfg = &ctrl->cfg; + vcl_test_client_worker_t *wrk; + uint32_t i, n_conn, n_conn_per_wrk; + + vtinf ("%s-directional Stream Test Starting!", + ctrl->cfg.test == VCL_TEST_TYPE_BI ? "Bi" : "Uni"); + + cfg->total_bytes = cfg->num_writes * cfg->txbuf_size; + cfg->ctrl_handle = ~0; + if (vtc_cfg_sync (ctrl)) + { + vtwrn ("test cfg sync failed -- aborting!"); + return; + } + cfg->ctrl_handle = ((vcl_test_cfg_t *) ctrl->rxbuf)->ctrl_handle; + memset (&ctrl->stats, 0, sizeof (ctrl->stats)); + + n_conn = cfg->num_test_sessions; + n_conn_per_wrk = n_conn / vcm->n_workers; + for (i = 0; i < vcm->n_workers; i++) + { + wrk = &vcm->workers[i]; + wrk->wrk_index = i; + wrk->cfg = ctrl->cfg; + wrk->cfg.num_test_sessions = vtc_min (n_conn_per_wrk, n_conn); + n_conn -= wrk->cfg.num_test_sessions; + } + + for (i = 1; i < vcm->n_workers; i++) + { + wrk = &vcm->workers[i]; + pthread_create (&wrk->thread_handle, NULL, vtc_worker_loop, + (void *) wrk); + } + vtc_worker_loop (&vcm->workers[0]); + + while (vcm->active_workers > 0) + ; + + vtinf ("Sending config on ctrl session (fd %d) for stats...", ctrl->fd); + if (vtc_cfg_sync (ctrl)) + { + vtwrn ("test cfg sync failed -- aborting!"); + return; + } + + vtc_print_stats (ctrl); + + ctrl->cfg.test = VCL_TEST_TYPE_ECHO; + ctrl->cfg.total_bytes = 0; + if (vtc_cfg_sync (ctrl)) + vtwrn ("post-test cfg sync failed!"); +} + +static void +dump_help (void) +{ +#define INDENT "\n " + + printf ("CLIENT: Test configuration commands:" + INDENT VCL_TEST_TOKEN_HELP + "\t\t\tDisplay help." + INDENT VCL_TEST_TOKEN_EXIT + "\t\t\tExit test client & server." + INDENT VCL_TEST_TOKEN_SHOW_CFG + "\t\t\tShow the current test cfg." + INDENT VCL_TEST_TOKEN_RUN_UNI + "\t\t\tRun the Uni-directional test." + INDENT VCL_TEST_TOKEN_RUN_BI + "\t\t\tRun the Bi-directional test." + INDENT VCL_TEST_TOKEN_VERBOSE + "\t\t\tToggle verbose setting." + INDENT VCL_TEST_TOKEN_RXBUF_SIZE + "\tRx buffer size (bytes)." + INDENT VCL_TEST_TOKEN_TXBUF_SIZE + "\tTx buffer size (bytes)." + INDENT VCL_TEST_TOKEN_NUM_WRITES + "<# of writes>\tNumber of txbuf writes to server." "\n"); +} + +static void +cfg_txbuf_size_set (void) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_TXBUF_SIZE); + uint64_t txbuf_size = strtoull ((const char *) p, NULL, 10); + + if (txbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->cfg.txbuf_size = txbuf_size; + ctrl->cfg.total_bytes = ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 0 /* is_rxbuf */ , + (uint8_t **) & ctrl->txbuf, &ctrl->txbuf_size); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + vtwrn ("Invalid txbuf size (%lu) < minimum buf size (%u)!", + txbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); +} + +static void +cfg_num_writes_set (void) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_NUM_WRITES); + uint32_t num_writes = strtoul ((const char *) p, NULL, 10); + + if (num_writes > 0) + { + ctrl->cfg.num_writes = num_writes; + ctrl->cfg.total_bytes = ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + { + vtwrn ("invalid num writes: %u", num_writes); + } +} + +static void +cfg_num_test_sessions_set (void) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_NUM_TEST_SESS); + uint32_t num_test_sessions = strtoul ((const char *) p, NULL, 10); + + if ((num_test_sessions > 0) && + (num_test_sessions <= VCL_TEST_CFG_MAX_TEST_SESS)) + { + ctrl->cfg.num_test_sessions = num_test_sessions; + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + { + vtwrn ("invalid num test sessions: %u, (%d max)", + num_test_sessions, VCL_TEST_CFG_MAX_TEST_SESS); + } +} + +static void +cfg_rxbuf_size_set (void) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + char *p = ctrl->txbuf + strlen (VCL_TEST_TOKEN_RXBUF_SIZE); + uint64_t rxbuf_size = strtoull ((const char *) p, NULL, 10); + + if (rxbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->cfg.rxbuf_size = rxbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 1 /* is_rxbuf */ , + (uint8_t **) & ctrl->rxbuf, &ctrl->rxbuf_size); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + else + vtwrn ("Invalid rxbuf size (%lu) < minimum buf size (%u)!", + rxbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); +} + +static void +cfg_verbose_toggle (void) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + + ctrl->cfg.verbose = ctrl->cfg.verbose ? 0 : 1; + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + +} + +static vcl_test_t +parse_input () +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + vcl_test_t rv = VCL_TEST_TYPE_NONE; + + if (!strncmp (VCL_TEST_TOKEN_EXIT, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_EXIT))) + rv = VCL_TEST_TYPE_EXIT; + + else if (!strncmp (VCL_TEST_TOKEN_HELP, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_HELP))) + dump_help (); + + else if (!strncmp (VCL_TEST_TOKEN_SHOW_CFG, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_SHOW_CFG))) + vcm->dump_cfg = 1; + + else if (!strncmp (VCL_TEST_TOKEN_VERBOSE, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_VERBOSE))) + cfg_verbose_toggle (); + + else if (!strncmp (VCL_TEST_TOKEN_TXBUF_SIZE, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_TXBUF_SIZE))) + cfg_txbuf_size_set (); + + else if (!strncmp (VCL_TEST_TOKEN_NUM_TEST_SESS, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_NUM_TEST_SESS))) + cfg_num_test_sessions_set (); + + else if (!strncmp (VCL_TEST_TOKEN_NUM_WRITES, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_NUM_WRITES))) + cfg_num_writes_set (); + + else if (!strncmp (VCL_TEST_TOKEN_RXBUF_SIZE, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_RXBUF_SIZE))) + cfg_rxbuf_size_set (); + + else if (!strncmp (VCL_TEST_TOKEN_RUN_UNI, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_RUN_UNI))) + rv = ctrl->cfg.test = VCL_TEST_TYPE_UNI; + + else if (!strncmp (VCL_TEST_TOKEN_RUN_BI, ctrl->txbuf, + strlen (VCL_TEST_TOKEN_RUN_BI))) + rv = ctrl->cfg.test = VCL_TEST_TYPE_BI; + + else + rv = VCL_TEST_TYPE_ECHO; + + return rv; +} + +void +print_usage_and_exit (void) +{ + fprintf (stderr, + "vcl_test_client [OPTIONS] \n" + " OPTIONS\n" + " -h Print this message and exit.\n" + " -6 Use IPv6\n" + " -c Print test config before test.\n" + " -w Write test results to .\n" + " -X Exit after running test.\n" + " -D Use UDP transport layer\n" + " -L Use TLS transport layer\n" + " -E Run Echo test.\n" + " -N Test Cfg: number of writes.\n" + " -R Test Cfg: rx buffer size.\n" + " -T Test Cfg: tx buffer size.\n" + " -U Run Uni-directional test.\n" + " -B Run Bi-directional test.\n" + " -V Verbose mode.\n"); + exit (1); +} + +static void +vtc_process_opts (vcl_test_client_main_t * vcm, int argc, char **argv) +{ + vcl_test_session_t *ctrl = &vcm->ctrl_session; + int c, v; + + opterr = 0; + while ((c = getopt (argc, argv, "chn:w:XE:I:N:R:T:UBV6DL")) != -1) + switch (c) + { + case 'c': + vcm->dump_cfg = 1; + break; + + case 's': + if (sscanf (optarg, "0x%x", &ctrl->cfg.num_test_sessions) != 1) + if (sscanf (optarg, "%u", &ctrl->cfg.num_test_sessions) != 1) + { + vtwrn ("Invalid value for option -%c!", c); + print_usage_and_exit (); + } + if (!ctrl->cfg.num_test_sessions || + (ctrl->cfg.num_test_sessions > FD_SETSIZE)) + { + vtwrn ("Invalid number of sessions (%d) specified for option -%c!" + "\n Valid range is 1 - %d", + ctrl->cfg.num_test_sessions, c, FD_SETSIZE); + print_usage_and_exit (); + } + break; + + case 'w': + if (sscanf (optarg, "%d", &v) != 1) + { + vtwrn ("Invalid value for option -%c!", c); + print_usage_and_exit (); + } + if (v > 1) + vcm->n_workers = v; + break; + + case 'X': + vcm->post_test = VCL_TEST_TYPE_EXIT; + break; + + case 'E': + if (strlen (optarg) > ctrl->txbuf_size) + { + vtwrn ("Option -%c value larger than txbuf size (%d)!", + optopt, ctrl->txbuf_size); + print_usage_and_exit (); + } + strcpy (ctrl->txbuf, optarg); + ctrl->cfg.test = VCL_TEST_TYPE_ECHO; + break; + + case 'I': + if (sscanf (optarg, "0x%x", &ctrl->cfg.num_test_sessions) != 1) + if (sscanf (optarg, "%d", &ctrl->cfg.num_test_sessions) != 1) + { + vtwrn ("Invalid value for option -%c!", c); + print_usage_and_exit (); + } + if (ctrl->cfg.num_test_sessions > VCL_TEST_CFG_MAX_TEST_SESS) + { + vtwrn ("value greater than max number test sessions (%d)!", + VCL_TEST_CFG_MAX_TEST_SESS); + print_usage_and_exit (); + } + break; + + case 'N': + if (sscanf (optarg, "0x%lx", &ctrl->cfg.num_writes) != 1) + if (sscanf (optarg, "%ld", &ctrl->cfg.num_writes) != 1) + { + vtwrn ("Invalid value for option -%c!", c); + print_usage_and_exit (); + } + ctrl->cfg.total_bytes = ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + break; + + case 'R': + if (sscanf (optarg, "0x%lx", &ctrl->cfg.rxbuf_size) != 1) + if (sscanf (optarg, "%ld", &ctrl->cfg.rxbuf_size) != 1) + { + vtwrn ("Invalid value for option -%c!", c); + print_usage_and_exit (); + } + if (ctrl->cfg.rxbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->rxbuf_size = ctrl->cfg.rxbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 1 /* is_rxbuf */ , + (uint8_t **) & ctrl->rxbuf, + &ctrl->rxbuf_size); + } + else + { + vtwrn ("rxbuf size (%lu) less than minumum (%u)", + ctrl->cfg.rxbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); + print_usage_and_exit (); + } + + break; + + case 'T': + if (sscanf (optarg, "0x%lx", &ctrl->cfg.txbuf_size) != 1) + if (sscanf (optarg, "%ld", &ctrl->cfg.txbuf_size) != 1) + { + vtwrn ("Invalid value for option -%c!", c); + print_usage_and_exit (); + } + if (ctrl->cfg.txbuf_size >= VCL_TEST_CFG_BUF_SIZE_MIN) + { + ctrl->txbuf_size = ctrl->cfg.txbuf_size; + vcl_test_buf_alloc (&ctrl->cfg, 0 /* is_rxbuf */ , + (uint8_t **) & ctrl->txbuf, + &ctrl->txbuf_size); + ctrl->cfg.total_bytes = + ctrl->cfg.num_writes * ctrl->cfg.txbuf_size; + } + else + { + vtwrn ("txbuf size (%lu) less than minumum (%u)!", + ctrl->cfg.txbuf_size, VCL_TEST_CFG_BUF_SIZE_MIN); + print_usage_and_exit (); + } + break; + + case 'U': + ctrl->cfg.test = VCL_TEST_TYPE_UNI; + break; + + case 'B': + ctrl->cfg.test = VCL_TEST_TYPE_BI; + break; + + case 'V': + ctrl->cfg.verbose = 1; + break; + + case '6': + ctrl->cfg.address_ip6 = 1; + break; + + case 'D': + ctrl->cfg.transport_udp = 1; + break; + + case 'L': + ctrl->cfg.transport_tls = 1; + break; + + case '?': + switch (optopt) + { + case 'E': + case 'I': + case 'N': + case 'R': + case 'T': + case 'w': + vtwrn ("Option -%c requires an argument.", optopt); + break; + + default: + if (isprint (optopt)) + vtwrn ("Unknown option `-%c'.", optopt); + else + vtwrn ("Unknown option character `\\x%x'.", optopt); + } + /* fall thru */ + case 'h': + default: + print_usage_and_exit (); + } + + if (argc < (optind + 2)) + { + vtwrn ("Insufficient number of arguments!"); + print_usage_and_exit (); + } + + if (ctrl->cfg.transport_udp) + { + vcm->proto = VPPCOM_PROTO_UDP; + } + else if (ctrl->cfg.transport_tls) + { + vcm->proto = VPPCOM_PROTO_TLS; + } + else + { + vcm->proto = VPPCOM_PROTO_TCP; + } + + memset (&vcm->server_addr, 0, sizeof (vcm->server_addr)); + if (ctrl->cfg.address_ip6) + { + struct sockaddr_in6 *sddr6 = (struct sockaddr_in6 *) &vcm->server_addr; + sddr6->sin6_family = AF_INET6; + inet_pton (AF_INET6, argv[optind++], &(sddr6->sin6_addr)); + sddr6->sin6_port = htons (atoi (argv[optind])); + + vcm->server_endpt.is_ip4 = 0; + vcm->server_endpt.ip = (uint8_t *) & sddr6->sin6_addr; + vcm->server_endpt.port = (uint16_t) sddr6->sin6_port; + } + else + { + struct sockaddr_in *saddr4 = (struct sockaddr_in *) &vcm->server_addr; + saddr4->sin_family = AF_INET; + inet_pton (AF_INET, argv[optind++], &(saddr4->sin_addr)); + saddr4->sin_port = htons (atoi (argv[optind])); + + vcm->server_endpt.is_ip4 = 1; + vcm->server_endpt.ip = (uint8_t *) & saddr4->sin_addr; + vcm->server_endpt.port = (uint16_t) saddr4->sin_port; + } +} + +static void +vtc_read_user_input (vcl_test_session_t * ctrl) +{ + printf ("\nType some characters and hit \n" + "('" VCL_TEST_TOKEN_HELP "' for help): "); + + if (fgets (ctrl->txbuf, ctrl->txbuf_size, stdin) != NULL) + { + if (strlen (ctrl->txbuf) == 1) + { + printf ("\nNothing to send! Please try again...\n"); + return; + } + ctrl->txbuf[strlen (ctrl->txbuf) - 1] = 0; // chomp the newline. + + /* Parse input for keywords */ + ctrl->cfg.test = parse_input (); + } +} + +static void +vtc_ctrl_session_exit (void) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + int verbose = ctrl->cfg.verbose; + + ctrl->cfg.test = VCL_TEST_TYPE_EXIT; + if (verbose) + { + vtinf ("(fd %d): Sending exit cfg to server...", ctrl->fd); + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + } + (void) vcl_test_write (ctrl->fd, (uint8_t *) & ctrl->cfg, + sizeof (ctrl->cfg), &ctrl->stats, verbose); + sleep (1); +} + +int +main (int argc, char **argv) +{ + vcl_test_client_main_t *vcm = &vcl_client_main; + vcl_test_session_t *ctrl = &vcm->ctrl_session; + int rv; + + vcm->n_workers = 1; + vcl_test_cfg_init (&ctrl->cfg); + vcl_test_session_buf_alloc (ctrl); + vtc_process_opts (vcm, argc, argv); + + vcm->workers = calloc (vcm->n_workers, sizeof (vcl_test_client_worker_t)); + rv = vppcom_app_create ("vcl_test_client"); + if (rv < 0) + vtfail ("vppcom_app_create()", rv); + + ctrl->fd = vppcom_session_create (vcm->proto, 0 /* is_nonblocking */ ); + if (ctrl->fd < 0) + vtfail ("vppcom_session_create()", ctrl->fd); + + if (vcm->proto == VPPCOM_PROTO_TLS) + { + vtinf ("Adding tls certs ..."); + vppcom_session_tls_add_cert (ctrl->fd, vcl_test_crt_rsa, + vcl_test_crt_rsa_len); + vppcom_session_tls_add_key (ctrl->fd, vcl_test_key_rsa, + vcl_test_key_rsa_len); + } + + vtinf ("Connecting to server..."); + rv = vppcom_session_connect (ctrl->fd, &vcm->server_endpt); + if (rv) + vtfail ("vppcom_session_connect()", rv); + vtinf ("Control session (fd %d) connected.", ctrl->fd); + + rv = vtc_cfg_sync (ctrl); + if (rv) + vtfail ("vtc_cfg_sync()", rv); + + ctrl->cfg.ctrl_handle = ((vcl_test_cfg_t *) ctrl->rxbuf)->ctrl_handle; + memset (&ctrl->stats, 0, sizeof (ctrl->stats)); + + while (ctrl->cfg.test != VCL_TEST_TYPE_EXIT) + { + if (vcm->dump_cfg) + { + vcl_test_cfg_dump (&ctrl->cfg, 1 /* is_client */ ); + vcm->dump_cfg = 0; + } + + switch (ctrl->cfg.test) + { + case VCL_TEST_TYPE_ECHO: + vtc_echo_client (vcm); + break; + + case VCL_TEST_TYPE_UNI: + case VCL_TEST_TYPE_BI: + vtc_stream_client (vcm); + break; + + case VCL_TEST_TYPE_EXIT: + continue; + + case VCL_TEST_TYPE_NONE: + default: + break; + } + switch (vcm->post_test) + { + case VCL_TEST_TYPE_EXIT: + switch (ctrl->cfg.test) + { + case VCL_TEST_TYPE_EXIT: + case VCL_TEST_TYPE_UNI: + case VCL_TEST_TYPE_BI: + case VCL_TEST_TYPE_ECHO: + ctrl->cfg.test = VCL_TEST_TYPE_EXIT; + continue; + + case VCL_TEST_TYPE_NONE: + default: + break; + } + break; + + case VCL_TEST_TYPE_NONE: + case VCL_TEST_TYPE_ECHO: + case VCL_TEST_TYPE_UNI: + case VCL_TEST_TYPE_BI: + default: + break; + } + + memset (ctrl->txbuf, 0, ctrl->txbuf_size); + memset (ctrl->rxbuf, 0, ctrl->rxbuf_size); + + vtc_read_user_input (ctrl); + } + + vtc_ctrl_session_exit (); + vppcom_session_close (ctrl->fd); + vppcom_app_destroy (); + free (vcm->workers); + return 0; +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/src/plugins/hs_apps/vcl/vcl_test_server.c b/src/plugins/hs_apps/vcl/vcl_test_server.c new file mode 100644 index 00000000000..62292adae5f --- /dev/null +++ b/src/plugins/hs_apps/vcl/vcl_test_server.c @@ -0,0 +1,743 @@ +/* + * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef struct +{ + uint8_t is_alloc; + int fd; + uint8_t *buf; + uint32_t buf_size; + vcl_test_cfg_t cfg; + vcl_test_stats_t stats; + vppcom_endpt_t endpt; + uint8_t ip[16]; + vppcom_data_segments_t ds; +} vcl_test_server_conn_t; + +typedef struct +{ + uint16_t port; + uint32_t address_ip6; + u8 proto; + u8 workers; + vppcom_endpt_t endpt; +} vcl_test_server_cfg_t; + +typedef struct +{ + uint32_t wrk_index; + int listen_fd; + int epfd; + struct epoll_event wait_events[VCL_TEST_CFG_MAX_EPOLL_EVENTS]; + size_t conn_pool_size; + vcl_test_server_conn_t *conn_pool; + int nfds; + pthread_t thread_handle; +} vcl_test_server_worker_t; + +typedef struct +{ + vcl_test_server_cfg_t cfg; + vcl_test_server_worker_t *workers; + + struct sockaddr_storage servaddr; + volatile int worker_fails; + volatile int active_workers; + u8 use_ds; +} vcl_test_server_main_t; + +static __thread int __wrk_index = 0; + +static vcl_test_server_main_t vcl_server_main; + +static inline void +conn_pool_expand (vcl_test_server_worker_t * wrk, size_t expand_size) +{ + vcl_test_server_conn_t *conn_pool; + size_t new_size = wrk->conn_pool_size + expand_size; + int i; + + conn_pool = realloc (wrk->conn_pool, new_size * sizeof (*wrk->conn_pool)); + if (conn_pool) + { + for (i = wrk->conn_pool_size; i < new_size; i++) + { + vcl_test_server_conn_t *conn = &conn_pool[i]; + memset (conn, 0, sizeof (*conn)); + vcl_test_cfg_init (&conn->cfg); + vcl_test_buf_alloc (&conn->cfg, 1 /* is_rxbuf */ , + &conn->buf, &conn->buf_size); + conn->cfg.txbuf_size = conn->cfg.rxbuf_size; + } + + wrk->conn_pool = conn_pool; + wrk->conn_pool_size = new_size; + } + else + { + vterr ("conn_pool_expand()", -errno); + } +} + +static inline vcl_test_server_conn_t * +conn_pool_alloc (vcl_test_server_worker_t * wrk) +{ + int i, expand = 0; + +again: + for (i = 0; i < wrk->conn_pool_size; i++) + { + if (!wrk->conn_pool[i].is_alloc) + { + wrk->conn_pool[i].endpt.ip = wrk->conn_pool[i].ip; + wrk->conn_pool[i].is_alloc = 1; + return (&wrk->conn_pool[i]); + } + } + + if (expand == 0) + { + conn_pool_expand (wrk, 2 * wrk->conn_pool_size); + expand = 1; + goto again; + } + vtwrn ("Failed to allocate connection even after expand"); + return 0; +} + +static inline void +conn_pool_free (vcl_test_server_conn_t * conn) +{ + conn->fd = 0; + conn->is_alloc = 0; +} + +static inline void +sync_config_and_reply (vcl_test_server_conn_t * conn, vcl_test_cfg_t * rx_cfg) +{ + conn->cfg = *rx_cfg; + vcl_test_buf_alloc (&conn->cfg, 1 /* is_rxbuf */ , + &conn->buf, &conn->buf_size); + conn->cfg.txbuf_size = conn->cfg.rxbuf_size; + + if (conn->cfg.verbose) + { + vtinf ("(fd %d): Replying to cfg message!\n", conn->fd); + vcl_test_cfg_dump (&conn->cfg, 0 /* is_client */ ); + } + (void) vcl_test_write (conn->fd, (uint8_t *) & conn->cfg, + sizeof (conn->cfg), NULL, conn->cfg.verbose); +} + +static void +vts_server_start_stop (vcl_test_server_worker_t * wrk, + vcl_test_server_conn_t * conn, vcl_test_cfg_t * rx_cfg) +{ + u8 is_bi = rx_cfg->test == VCL_TEST_TYPE_BI; + vcl_test_server_conn_t *tc; + char buf[64]; + int i; + + if (rx_cfg->ctrl_handle == conn->fd) + { + for (i = 0; i < wrk->conn_pool_size; i++) + { + tc = &wrk->conn_pool[i]; + if (tc->cfg.ctrl_handle != conn->fd) + continue; + + vcl_test_stats_accumulate (&conn->stats, &tc->stats); + if (vcl_comp_tspec (&conn->stats.stop, &tc->stats.stop) < 0) + conn->stats.stop = tc->stats.stop; + /* Client delays sending of disconnect */ + conn->stats.stop.tv_sec -= VCL_TEST_DELAY_DISCONNECT; + if (conn->cfg.verbose) + { + sprintf (buf, "SERVER (fd %d) RESULTS", tc->fd); + vcl_test_stats_dump (buf, &tc->stats, 1 /* show_rx */ , + is_bi /* show tx */ , conn->cfg.verbose); + } + } + + vcl_test_stats_dump ("SERVER RESULTS", &conn->stats, 1 /* show_rx */ , + is_bi /* show_tx */ , conn->cfg.verbose); + vcl_test_cfg_dump (&conn->cfg, 0 /* is_client */ ); + if (conn->cfg.verbose) + { + vtinf (" vcl server main\n" + VCL_TEST_SEPARATOR_STRING + " buf: %p\n" + " buf size: %u (0x%08x)\n" + VCL_TEST_SEPARATOR_STRING, + conn->buf, conn->buf_size, conn->buf_size); + } + + sync_config_and_reply (conn, rx_cfg); + memset (&conn->stats, 0, sizeof (conn->stats)); + } + else + { + if (rx_cfg->ctrl_handle == ~0) + { + rx_cfg->ctrl_handle = conn->fd; + vtinf ("Set control fd %d for test!", conn->fd); + } + else + { + vtinf ("Starting %s-directional Stream Test (fd %d)!", + is_bi ? "Bi" : "Uni", conn->fd); + } + + sync_config_and_reply (conn, rx_cfg); + + /* read the 1st chunk, record start time */ + memset (&conn->stats, 0, sizeof (conn->stats)); + clock_gettime (CLOCK_REALTIME, &conn->stats.start); + } +} + +static inline void +vts_server_rx (vcl_test_server_conn_t * conn, int rx_bytes) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + int client_fd = conn->fd; + + if (conn->cfg.test == VCL_TEST_TYPE_BI) + { + if (vsm->use_ds) + { + (void) vcl_test_write (client_fd, conn->ds[0].data, conn->ds[0].len, + &conn->stats, conn->cfg.verbose); + if (conn->ds[1].len) + (void) vcl_test_write (client_fd, conn->ds[1].data, + conn->ds[1].len, &conn->stats, + conn->cfg.verbose); + } + else + (void) vcl_test_write (client_fd, conn->buf, rx_bytes, &conn->stats, + conn->cfg.verbose); + } + + if (vsm->use_ds) + vppcom_session_free_segments (conn->fd, conn->ds); + + if (conn->stats.rx_bytes >= conn->cfg.total_bytes) + clock_gettime (CLOCK_REALTIME, &conn->stats.stop); +} + +static void +vts_server_echo (vcl_test_server_conn_t * conn, int rx_bytes) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + int tx_bytes, nbytes, pos; + + if (vsm->use_ds) + vppcom_data_segment_copy (conn->buf, conn->ds, rx_bytes); + + /* If it looks vaguely like a string, make sure it's terminated */ + pos = rx_bytes < conn->buf_size ? rx_bytes : conn->buf_size - 1; + ((char *) conn->buf)[pos] = 0; + vtinf ("(fd %d): RX (%d bytes) - '%s'", conn->fd, rx_bytes, conn->buf); + + if (conn->cfg.verbose) + vtinf ("(fd %d): Echoing back", conn->fd); + + nbytes = strlen ((const char *) conn->buf) + 1; + tx_bytes = vcl_test_write (conn->fd, conn->buf, nbytes, &conn->stats, + conn->cfg.verbose); + if (tx_bytes >= 0) + vtinf ("(fd %d): TX (%d bytes) - '%s'", conn->fd, tx_bytes, conn->buf); +} + +static void +vts_new_client (vcl_test_server_worker_t * wrk) +{ + vcl_test_server_conn_t *conn; + struct epoll_event ev; + int rv, client_fd; + + conn = conn_pool_alloc (wrk); + if (!conn) + { + vtwrn ("No free connections!"); + return; + } + + client_fd = vppcom_session_accept (wrk->listen_fd, &conn->endpt, 0); + if (client_fd < 0) + { + vterr ("vppcom_session_accept()", client_fd); + return; + } + conn->fd = client_fd; + + vtinf ("Got a connection -- fd = %d (0x%08x)!", client_fd, client_fd); + + ev.events = EPOLLIN; + ev.data.u64 = conn - wrk->conn_pool; + rv = vppcom_epoll_ctl (wrk->epfd, EPOLL_CTL_ADD, client_fd, &ev); + if (rv < 0) + { + vterr ("vppcom_epoll_ctl()", rv); + return; + } + wrk->nfds++; +} + +static void +print_usage_and_exit (void) +{ + fprintf (stderr, + "vcl_test_server [OPTIONS] \n" + " OPTIONS\n" + " -h Print this message and exit.\n" + " -6 Use IPv6\n" + " -w Number of workers\n" + " -D Use UDP transport layer\n" + " -L Use TLS transport layer\n"); + exit (1); +} + +static void +vcl_test_init_endpoint_addr (vcl_test_server_main_t * vsm) +{ + struct sockaddr_storage *servaddr = &vsm->servaddr; + memset (servaddr, 0, sizeof (*servaddr)); + + if (vsm->cfg.address_ip6) + { + struct sockaddr_in6 *server_addr = (struct sockaddr_in6 *) servaddr; + server_addr->sin6_family = AF_INET6; + server_addr->sin6_addr = in6addr_any; + server_addr->sin6_port = htons (vsm->cfg.port); + } + else + { + struct sockaddr_in *server_addr = (struct sockaddr_in *) servaddr; + server_addr->sin_family = AF_INET; + server_addr->sin_addr.s_addr = htonl (INADDR_ANY); + server_addr->sin_port = htons (vsm->cfg.port); + } + + if (vsm->cfg.address_ip6) + { + struct sockaddr_in6 *server_addr = (struct sockaddr_in6 *) servaddr; + vsm->cfg.endpt.is_ip4 = 0; + vsm->cfg.endpt.ip = (uint8_t *) & server_addr->sin6_addr; + vsm->cfg.endpt.port = (uint16_t) server_addr->sin6_port; + } + else + { + struct sockaddr_in *server_addr = (struct sockaddr_in *) servaddr; + vsm->cfg.endpt.is_ip4 = 1; + vsm->cfg.endpt.ip = (uint8_t *) & server_addr->sin_addr; + vsm->cfg.endpt.port = (uint16_t) server_addr->sin_port; + } +} + +static void +vcl_test_server_process_opts (vcl_test_server_main_t * vsm, int argc, + char **argv) +{ + int v, c; + + vsm->cfg.proto = VPPCOM_PROTO_TCP; + + opterr = 0; + while ((c = getopt (argc, argv, "6DLsw:")) != -1) + switch (c) + { + case '6': + vsm->cfg.address_ip6 = 1; + break; + + case 'D': + vsm->cfg.proto = VPPCOM_PROTO_UDP; + break; + + case 'L': + vsm->cfg.proto = VPPCOM_PROTO_TLS; + break; + + case 'w': + v = atoi (optarg); + if (v > 1) + vsm->cfg.workers = v; + else + vtwrn ("Invalid number of workers %d", v); + break; + case 's': + vsm->use_ds = 1; + break; + case '?': + switch (optopt) + { + default: + if (isprint (optopt)) + vtwrn ("Unknown option `-%c'.", optopt); + else + vtwrn ("Unknown option character `\\x%x'.", optopt); + } + /* fall thru */ + case 'h': + default: + print_usage_and_exit (); + } + + if (argc < (optind + 1)) + { + fprintf (stderr, "SERVER: ERROR: Insufficient number of arguments!\n"); + print_usage_and_exit (); + } + + if (sscanf (argv[optind], "%d", &v) == 1) + vsm->cfg.port = (uint16_t) v; + else + { + fprintf (stderr, "SERVER: ERROR: Invalid port (%s)!\n", argv[optind]); + print_usage_and_exit (); + } + + vcl_test_init_endpoint_addr (vsm); +} + +int +vts_handle_cfg (vcl_test_server_worker_t * wrk, vcl_test_cfg_t * rx_cfg, + vcl_test_server_conn_t * conn, int rx_bytes) +{ + if (rx_cfg->verbose) + { + vtinf ("(fd %d): Received a cfg msg!", conn->fd); + vcl_test_cfg_dump (rx_cfg, 0 /* is_client */ ); + } + + if (rx_bytes != sizeof (*rx_cfg)) + { + vtinf ("(fd %d): Invalid cfg msg size %d expected %lu!", conn->fd, + rx_bytes, sizeof (*rx_cfg)); + conn->cfg.rxbuf_size = 0; + conn->cfg.num_writes = 0; + if (conn->cfg.verbose) + { + vtinf ("(fd %d): Replying to cfg msg", conn->fd); + vcl_test_cfg_dump (rx_cfg, 0 /* is_client */ ); + } + vcl_test_write (conn->fd, (uint8_t *) & conn->cfg, + sizeof (conn->cfg), NULL, conn->cfg.verbose); + return -1; + } + + switch (rx_cfg->test) + { + case VCL_TEST_TYPE_NONE: + case VCL_TEST_TYPE_ECHO: + sync_config_and_reply (conn, rx_cfg); + break; + + case VCL_TEST_TYPE_BI: + case VCL_TEST_TYPE_UNI: + vts_server_start_stop (wrk, conn, rx_cfg); + break; + + case VCL_TEST_TYPE_EXIT: + vtinf ("Session fd %d closing!", conn->fd); + clock_gettime (CLOCK_REALTIME, &conn->stats.stop); + vppcom_session_close (conn->fd); + conn_pool_free (conn); + wrk->nfds--; + break; + + default: + vtwrn ("Unknown test type %d", rx_cfg->test); + vcl_test_cfg_dump (rx_cfg, 0 /* is_client */ ); + break; + } + + return 0; +} + +static void +vts_worker_init (vcl_test_server_worker_t * wrk) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + struct epoll_event listen_ev; + int rv; + + __wrk_index = wrk->wrk_index; + + vtinf ("Initializing worker ..."); + + conn_pool_expand (wrk, VCL_TEST_CFG_MAX_TEST_SESS + 1); + if (wrk->wrk_index) + if (vppcom_worker_register ()) + vtfail ("vppcom_worker_register()", 1); + + wrk->listen_fd = vppcom_session_create (vsm->cfg.proto, + 0 /* is_nonblocking */ ); + if (wrk->listen_fd < 0) + vtfail ("vppcom_session_create()", wrk->listen_fd); + + + if (vsm->cfg.proto == VPPCOM_PROTO_TLS) + { + vppcom_session_tls_add_cert (wrk->listen_fd, vcl_test_crt_rsa, + vcl_test_crt_rsa_len); + vppcom_session_tls_add_key (wrk->listen_fd, vcl_test_key_rsa, + vcl_test_key_rsa_len); + } + + rv = vppcom_session_bind (wrk->listen_fd, &vsm->cfg.endpt); + if (rv < 0) + vtfail ("vppcom_session_bind()", rv); + + if (!(vsm->cfg.proto == VPPCOM_PROTO_UDP)) + { + rv = vppcom_session_listen (wrk->listen_fd, 10); + if (rv < 0) + vtfail ("vppcom_session_listen()", rv); + } + + wrk->epfd = vppcom_epoll_create (); + if (wrk->epfd < 0) + vtfail ("vppcom_epoll_create()", wrk->epfd); + + listen_ev.events = EPOLLIN; + listen_ev.data.u32 = ~0; + rv = vppcom_epoll_ctl (wrk->epfd, EPOLL_CTL_ADD, wrk->listen_fd, + &listen_ev); + if (rv < 0) + vtfail ("vppcom_epoll_ctl", rv); + + vsm->active_workers += 1; + vtinf ("Waiting for a client to connect on port %d ...", vsm->cfg.port); +} + +static int +vts_conn_expect_config (vcl_test_server_conn_t * conn) +{ + if (conn->cfg.test == VCL_TEST_TYPE_ECHO) + return 1; + + return (conn->stats.rx_bytes < 128 + || conn->stats.rx_bytes > conn->cfg.total_bytes); +} + +static vcl_test_cfg_t * +vts_conn_read_config (vcl_test_server_conn_t * conn) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + + if (vsm->use_ds) + { + /* We could avoid the copy if the first segment is big enough but this + * just simplifies things */ + vppcom_data_segment_copy (conn->buf, conn->ds, sizeof (vcl_test_cfg_t)); + } + return (vcl_test_cfg_t *) conn->buf; +} + +static inline int +vts_conn_read (vcl_test_server_conn_t * conn) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + if (vsm->use_ds) + return vcl_test_read_ds (conn->fd, conn->ds, &conn->stats); + else + return vcl_test_read (conn->fd, conn->buf, conn->buf_size, &conn->stats); +} + +static inline int +vts_conn_has_ascii (vcl_test_server_conn_t * conn) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + + if (vsm->use_ds) + return isascii (conn->ds[0].data[0]); + else + return isascii (conn->buf[0]); +} + +static void * +vts_worker_loop (void *arg) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + vcl_test_server_worker_t *wrk = arg; + vcl_test_server_conn_t *conn; + int i, rx_bytes, num_ev; + vcl_test_cfg_t *rx_cfg; + + if (wrk->wrk_index) + vts_worker_init (wrk); + + while (1) + { + num_ev = vppcom_epoll_wait (wrk->epfd, wrk->wait_events, + VCL_TEST_CFG_MAX_EPOLL_EVENTS, 60000.0); + if (num_ev < 0) + { + vterr ("vppcom_epoll_wait()", num_ev); + goto fail; + } + else if (num_ev == 0) + { + vtinf ("vppcom_epoll_wait() timeout!"); + continue; + } + for (i = 0; i < num_ev; i++) + { + conn = &wrk->conn_pool[wrk->wait_events[i].data.u32]; + if (wrk->wait_events[i].events & (EPOLLHUP | EPOLLRDHUP)) + { + vppcom_session_close (conn->fd); + wrk->nfds -= 1; + if (!wrk->nfds) + { + vtinf ("All client connections closed\n"); + goto done; + } + continue; + } + if (wrk->wait_events[i].data.u32 == ~0) + { + vts_new_client (wrk); + continue; + } + + if (EPOLLIN & wrk->wait_events[i].events) + { + read_again: + rx_bytes = vts_conn_read (conn); + + if (rx_bytes <= 0) + { + if (errno == ECONNRESET) + { + vtinf ("Connection reset by remote peer.\n"); + goto fail; + } + else + continue; + } + + if (vts_conn_expect_config (conn)) + { + rx_cfg = vts_conn_read_config (conn); + if (rx_cfg->magic == VCL_TEST_CFG_CTRL_MAGIC) + { + if (vsm->use_ds) + vppcom_session_free_segments (conn->fd, conn->ds); + vts_handle_cfg (wrk, rx_cfg, conn, rx_bytes); + if (!wrk->nfds) + { + vtinf ("All client connections closed\n"); + goto done; + } + continue; + } + } + if ((conn->cfg.test == VCL_TEST_TYPE_UNI) + || (conn->cfg.test == VCL_TEST_TYPE_BI)) + { + vts_server_rx (conn, rx_bytes); + if (vppcom_session_attr (conn->fd, VPPCOM_ATTR_GET_NREAD, 0, + 0) > 0) + goto read_again; + continue; + } + if (vts_conn_has_ascii (conn)) + { + vts_server_echo (conn, rx_bytes); + } + else + { + vtwrn ("FIFO not drained! extra bytes %d", rx_bytes); + } + } + else + { + vtwrn ("Unhandled event"); + goto fail; + } + } + } + +fail: + vsm->worker_fails -= 1; + +done: + vppcom_session_close (wrk->listen_fd); + if (wrk->conn_pool) + free (wrk->conn_pool); + vsm->active_workers -= 1; + return 0; +} + +int +main (int argc, char **argv) +{ + vcl_test_server_main_t *vsm = &vcl_server_main; + int rv, i; + + clib_mem_init_thread_safe (0, 64 << 20); + vsm->cfg.port = VCL_TEST_SERVER_PORT; + vsm->cfg.workers = 1; + vsm->active_workers = 0; + vcl_test_server_process_opts (vsm, argc, argv); + + rv = vppcom_app_create ("vcl_test_server"); + if (rv) + vtfail ("vppcom_app_create()", rv); + + vsm->workers = calloc (vsm->cfg.workers, sizeof (*vsm->workers)); + vts_worker_init (&vsm->workers[0]); + for (i = 1; i < vsm->cfg.workers; i++) + { + vsm->workers[i].wrk_index = i; + rv = pthread_create (&vsm->workers[i].thread_handle, NULL, + vts_worker_loop, (void *) &vsm->workers[i]); + } + vts_worker_loop (&vsm->workers[0]); + + while (vsm->active_workers > 0) + ; + + vppcom_app_destroy (); + free (vsm->workers); + + return vsm->worker_fails; +} + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ -- cgit 1.2.3-korg