Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @file testsPubSub.c
- *
- * @brief Implements tests for the PUB-SUB pattern.
- */
- #define _BSD_SOURCE // TODO: required for usleep()
- /***********************************************************
- * INCLUDES
- ***********************************************************/
- #include <stdio.h>
- #include <stdint.h>
- #include <string.h>
- #include <assert.h>
- #include <pthread.h>
- #include <signal.h>
- #include <unistd.h>
- #include <zmq.h>
- /***********************************************************
- * SWITCHES
- ***********************************************************/
- /**
- * Defines if debug output is generated. Output is generated
- * on stderr. Possible values are:
- * - 0: no debug output
- * - 1: generate debug output
- *
- * @see DPRINTF()
- */
- #define USE_DPRINTF 1
- /**
- * Defines which type of communication is used. Possible
- * values are:
- * - 0: inproc (inter-thread communication)
- * - 1: ipc (inter-process communication)
- * - 2: tcp (TCP/IP sockets)
- *
- * @see ENDPOINT_FORMAT_STRING
- */
- #define TYPE_SOCKET 1
- /**
- * The number of main loops are executed by the clients.
- * Must be a positive number.
- */
- #define COUNT_LOOPS 3
- /**
- * The number of endpoints used by some tests. That means
- * both the number of servers and the number of clients
- * generated for 1 to n, n to 1 or n to m tests. Must be
- * a positive number.
- * @see SERVER_MAX
- * @see CLIENT_MAX
- * @see REQUESTER_MAX
- */
- #define COUNT_ENDPOINTS 3
- /**
- * The number of microseconds used to simulate a busy
- * server and to delay the response messages. Must be zero
- * for no delay or a positive number.
- */
- #define SERVER_BUSY_MICROSECS (0 * 1000)
- /**
- * The number of microseconds used to delay server before
- * closing a socket. Required, because subscibers will
- * lose last messages. Must be zero for no delay
- * or a positive number.
- */
- #define SERVER_CLEANUP_MICROSECS (10 * 1000)
- /**
- * The number of microseconds used to delay server after
- * creating a socket. Required, because subscibers will
- * lose first messages. Must be zero for no delay
- * or a positive number.
- */
- #define CLIENT_STARTUP_MICROSECS (500 * 1000)
- /***********************************************************
- * COMMON DEFINITIONS
- ***********************************************************/
- #ifndef FALSE
- /**
- * Standard value for false, if not defined already.
- * @see TRUE
- */
- #define FALSE 0
- #endif
- #ifndef TRUE
- /**
- * Standard value for true, if not defined already.
- * @see FALSE
- */
- #define TRUE (!FALSE)
- #endif
- #if (TYPE_SOCKET == 0)
- /**
- * The format string used for inproc communication.
- * @see TYPE_SOCKET
- */
- #define ENDPOINT_FORMAT_STRING "inproc://inproc-%d"
- #elif (TYPE_SOCKET == 1)
- /**
- * The format string used for ipc communication.
- * @see TYPE_SOCKET
- */
- #define ENDPOINT_FORMAT_STRING "ipc://ipc-%d.ipc"
- #elif (TYPE_SOCKET == 2)
- /**
- * The format string used for tcp communication.
- * @see TYPE_SOCKET
- */
- #define ENDPOINT_FORMAT_STRING "tcp://%s:%d"
- #else
- #error Wrong value for socket type, must be in [0, 2]
- #endif
- /**
- * The maximum number of servers used by some tests. Some tests
- * uses a single server and some test uses this maximum number
- * of servers.
- * @see COUNT_ENDPOINTS
- */
- #define SERVER_MAX COUNT_ENDPOINTS
- /**
- * The maximum number of clients used by some tests. Some tests
- * uses a single client and some test uses this maximum number
- * of clients.
- * @see SERVER_MAX
- */
- #define CLIENT_MAX SERVER_MAX
- /**
- * The maximum number of concurrent requests fo a single client
- * used by some tests. Some tests uses a single request and some
- * test uses this maximum number of requests.
- * @see SERVER_MAX
- */
- #define REQUESTER_MAX SERVER_MAX
- /***********************************************************
- * HELPER MACROS
- ***********************************************************/
- /**
- * Standard macro calculating the number of elements for
- * an array.
- */
- #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
- /**
- * Threadsafe replacement for CU_ASSERT_EQUAL().
- */
- #define MY_ASSERT_EQUAL(actual, expected) { \
- pthread_mutex_lock(&g_critical); \
- if (actual != expected) errors += 1; \
- pthread_mutex_unlock(&g_critical); \
- }
- #if (USE_DPRINTF == 0)
- /**
- * The empty debug output macro.
- * @see USE_DPRINTF
- */
- #define DPRINTF(...)
- #elif (USE_DPRINTF == 1)
- /**
- * The debug output macro to generate output on stderr.
- * @see USE_DPRINTF
- */
- #define DPRINTF(...) fprintf(stderr, ##__VA_ARGS__)
- #else
- #error Wrong value for debug output, must be in [0, 1]
- #endif
- /***********************************************************
- * HELPER FUNCTIONS
- ***********************************************************/
- /**
- * Generates a string for the name of a communication
- * endpoint. Used by servers.
- *
- * @param pBuffer buffer pointer used for the string
- * @param size size of the buffer
- * @param index index of the server
- *
- * @return pBuffer as the pointer to the resulting string
- *
- * @see endpointClient()
- * @see TYPE_SOCKET
- * @see ENDPOINT_FORMAT_STRING
- */
- char *endpointServer(char *pBuffer, size_t size, int index) {
- int ret;
- assert(pBuffer != NULL);
- #if (TYPE_SOCKET != 2) /* not TCP */
- ret = sprintf(pBuffer, ENDPOINT_FORMAT_STRING, index);
- assert(ret >= 0);
- assert(ret < (int) size);
- #else /* TCP */
- ret = sprintf(pBuffer, ENDPOINT_FORMAT_STRING, "*", 5000 + index);
- assert(ret >= 0);
- assert(ret < (int) size);
- #endif
- return pBuffer;
- }
- /**
- * Generates a string for the name of a communication
- * endpoint. Used by clients.
- *
- * @param pBuffer buffer pointer used for the string
- * @param size size of the buffer
- * @param index index of the server
- *
- * @return pBuffer as the pointer to the resulting string
- *
- * @see endpointServer()
- * @see TYPE_SOCKET
- * @see ENDPOINT_FORMAT_STRING
- */
- char *endpointClient(char *pBuffer, size_t size, int index) {
- int ret;
- assert(pBuffer != NULL);
- #if (TYPE_SOCKET != 2) /* not TCP */
- ret = sprintf(pBuffer, ENDPOINT_FORMAT_STRING, index);
- assert(ret >= 0);
- assert(ret < (int) size);
- #else /* TCP */
- ret = sprintf(pBuffer, ENDPOINT_FORMAT_STRING, "localhost", 5000 + index);
- assert(ret >= 0);
- assert(ret < (int) size);
- #endif
- return pBuffer;
- }
- /**
- * Sleeps a number of micro-seconds.
- *
- * @param usecs Microseconds to sleep
- *
- * @return native function return value, zero for success
- */
- int microsleep(int usecs) {
- return usleep(usecs); // TODO: replace with nanosleep()
- }
- /***********************************************************
- * DATA
- ***********************************************************/
- pthread_mutex_t g_critical = PTHREAD_MUTEX_INITIALIZER;
- int errors = 0;
- /***********************************************************
- * DATA STRUCTURES
- ***********************************************************/
- /**
- * Thread data structure for servers.
- * @see threadServer()
- */
- typedef struct THREAD_DATA_SERVER_T {
- /** The 0MQ content handle, created outside the thread. */
- void *zmqContext;
- /** Index of the server thread as unique server ID. */
- int threadIndex;
- /** Number of total test loops. */
- int loopCount;
- /** Run flag used to startup the server. */
- int bRun;
- /** Original thread ID. */
- pthread_t threadId;
- } THREAD_DATA_SERVER;
- /**
- * Thread data structure for clients.
- * @see threadClient()
- */
- typedef struct THREAD_DATA_CLIENT_T {
- /** The 0MQ content handle, created outside the thread. */
- void *zmqContext;
- /** Index of the client thread as unique client ID. */
- int threadIndex;
- /** Number of predicted correct sequences. */
- int seqCount;
- /** Number of parallel publishers. */
- int publisherCount;
- /** Run flag used to shutdown the server when done. */
- int bRun;
- /** Original thread ID. */
- pthread_t threadId;
- } THREAD_DATA_CLIENT;
- /**
- * The message structure used between clients and servers.
- */
- typedef struct MESSAGE_T {
- /**
- * The index as an ID from the sending client. Required
- * for the test.
- */
- int serverIndex;
- /**
- * A unique sequence number passed by a client
- * to a server.
- */
- int sequence;
- /**
- * Some data to simulate big packages.
- */
- char szText[1000];
- } MESSAGE;
- /***********************************************************
- * THREADS - SERVER
- ***********************************************************/
- /**
- * Server thread entry point.
- *
- * @param pArg pthread style argument pointer
- *
- * NULL is used as termination vaule.
- *
- * A pointer to a instance of a THREAD_DATA_SERVER
- * data structure is passed to the server thread using the
- * pArg parameter.
- *
- * @see THREAD_DATA_SERVER
- * @see MESSAGE
- * @see threadClient()
- */
- static void *threadServer (void *pArg) {
- THREAD_DATA_SERVER *pThreadData;
- void *zmqSocket;
- char text[40];
- int ret;
- zmq_msg_t zmqMsg;
- MESSAGE msg;
- int seq;
- int i;
- /* Initialization */
- assert(pArg != NULL);
- pThreadData = (THREAD_DATA_SERVER *) pArg;
- /* Sockets for publishing */
- zmqSocket = zmq_socket(pThreadData->zmqContext, ZMQ_PUB);
- assert(zmqSocket != NULL);
- ret = zmq_bind(zmqSocket, endpointServer(text, sizeof(text), pThreadData->threadIndex));
- assert(ret == 0);
- /* wait until runflag is set */
- while (!pThreadData->bRun) {
- microsleep(1 * 1000);
- }
- seq = 0;
- for (i = 0; i < pThreadData->loopCount; i += 1) {
- /* Initialize message for send */
- memset(&msg, -1, sizeof(msg));
- msg.serverIndex = pThreadData->threadIndex;
- msg.sequence = seq;
- sprintf(msg.szText, "%d-%d-%d", pThreadData->threadIndex, msg.serverIndex, msg.sequence);
- ret = zmq_msg_init_data(&zmqMsg, &msg, sizeof(msg), NULL, NULL);
- assert(ret == 0);
- DPRINTF("Server[%d]: out-message = [%d, %d, %s]\n",
- pThreadData->threadIndex, msg.serverIndex, msg.sequence, msg.szText);
- /* Send message */
- ret = zmq_send(zmqSocket, &zmqMsg, 0);
- assert(ret == 0);
- /* Close message resource */
- ret = zmq_msg_close(&zmqMsg);
- assert(ret == 0);
- seq += 1;
- /* Do some 'work' */
- // ret = microsleep (SERVER_BUSY_MICROSECS);
- // assert(ret == 0);
- }
- /* Final tests */
- MY_ASSERT_EQUAL(seq, pThreadData->loopCount);
- if (seq != (pThreadData->loopCount)) {
- DPRINTF("Client[%d]: sequence count = %d, assumed %d\n",
- pThreadData->threadIndex, seq,
- pThreadData->loopCount);
- }
- /* Give clients time to receive all */
- ret = microsleep (SERVER_CLEANUP_MICROSECS);
- assert(ret == 0);
- /* Cleanup */
- ret = zmq_close(zmqSocket);
- assert(ret == 0);
- /* Terminate thread */
- pthread_exit(NULL);
- assert(0);
- return NULL;
- }
- /***********************************************************
- * THREADS - CLIENT
- ***********************************************************/
- /**
- * Client thread entry point.
- *
- * @param pArg pthread style argument pointer
- *
- * NULL is used as termination vaule.
- *
- * A pointer to a instance of a THREAD_DATA_CLIENT
- * data structure is passed to the client thread using the
- * pArg parameter.
- *
- * @see THREAD_DATA_CLIENT
- * @see MESSAGE()
- * @see threadServer()
- */
- static void *threadClient (void *pArg) {
- THREAD_DATA_CLIENT *pThreadData;
- void *zmqSocket;
- char text[80];
- int i;
- int ii;
- int ret;
- zmq_pollitem_t zmqPollItem;
- zmq_msg_t zmqMsg;
- MESSAGE msg;
- int seq;
- int assumedServerSeq[SERVER_MAX];
- int countServerSeq[SERVER_MAX][COUNT_LOOPS];
- /* Initialization */
- assert(pArg != NULL);
- pThreadData = (THREAD_DATA_CLIENT *) pArg;
- assert(pThreadData->publisherCount <= REQUESTER_MAX);
- assert(pThreadData->seqCount <= COUNT_LOOPS);
- memset(assumedServerSeq, 0, sizeof(assumedServerSeq));
- memset(countServerSeq, 0, sizeof(countServerSeq));
- /* Socket to all publishers */
- zmqSocket = zmq_socket(pThreadData->zmqContext, ZMQ_SUB);
- assert(zmqSocket != NULL);
- ret = zmq_setsockopt (zmqSocket, ZMQ_SUBSCRIBE, "", 0);
- assert(ret == 0);
- for (i = 0; i < pThreadData->publisherCount; i += 1) {
- ret = zmq_connect(zmqSocket, endpointClient(text, sizeof(text), i));
- assert(ret == 0);
- }
- seq = 0;
- /* Prepare for polling */
- zmqPollItem.socket = zmqSocket;
- zmqPollItem.events = ZMQ_POLLIN;
- while (pThreadData->bRun) {
- /* Poll for the next event */
- ret = zmq_poll(&zmqPollItem, 1, 10 * 1000);
- assert(ret >= 0);
- if (ret > 0)
- {
- assert(ret == 1);
- assert(zmqPollItem.revents == ZMQ_POLLIN);
- /* Read next message */
- ret = zmq_msg_init(&zmqMsg);
- assert(ret == 0);
- ret = zmq_recv(zmqSocket, &zmqMsg, 0);
- assert(ret == 0);
- /* Get message content */
- assert(zmq_msg_size(&zmqMsg) == sizeof(msg));
- memcpy(&msg, zmq_msg_data(&zmqMsg), sizeof(msg));
- /* Close message */
- ret = zmq_msg_close(&zmqMsg);
- assert(ret == 0);
- DPRINTF("Client[%d]: in-message = [%d, %d, %s]\n",
- pThreadData->threadIndex, msg.serverIndex, msg.sequence, msg.szText);
- if (assumedServerSeq[msg.serverIndex] != msg.sequence) {
- DPRINTF("Client[%d]: wrong message received; assumed: message [%d, %d], received: [%d, %d], %d times\n",
- pThreadData->threadIndex,
- msg.serverIndex, assumedServerSeq[msg.serverIndex],
- msg.serverIndex, msg.sequence,
- countServerSeq[msg.serverIndex][msg.sequence]);
- }
- /* Check message */
- MY_ASSERT_EQUAL(assumedServerSeq[msg.serverIndex], msg.sequence);
- assumedServerSeq[msg.serverIndex] = msg.sequence + 1;
- /* Record sequence */
- MY_ASSERT_EQUAL(countServerSeq[msg.serverIndex][msg.sequence], 0);
- countServerSeq[msg.serverIndex][msg.sequence] += 1;
- seq += 1;
- }
- }
- /* Final tests */
- MY_ASSERT_EQUAL(seq, pThreadData->seqCount * pThreadData->publisherCount);
- for (i = 0; i < pThreadData->publisherCount; i += 1) {
- for (ii = 0; ii < pThreadData->seqCount; ii += 1) {
- MY_ASSERT_EQUAL(countServerSeq[i][ii], 1);
- if (countServerSeq[i][ii] != 1) {
- DPRINTF("Client[%d]: wrong number of messages received for [%d][%d]; assumed 1, received: %d\n",
- pThreadData->threadIndex, i, ii, countServerSeq[i][ii]);
- }
- }
- }
- if (seq != (pThreadData->seqCount * pThreadData->publisherCount)) {
- DPRINTF("Client[%d]: sequence count = %d, assumed %d\n",
- pThreadData->threadIndex, seq,
- pThreadData->seqCount * pThreadData->publisherCount);
- }
- /* Cleanup */
- ret = zmq_close(zmqSocket);
- assert(ret == 0);
- /* Terminate thread */
- pthread_exit(NULL);
- assert(0);
- return NULL;
- }
- /***********************************************************
- * LOCAL TESTS
- ***********************************************************/
- /**
- * Perform the test with configurable task numbers.
- *
- * @param clients Number of clients to start
- * @param servers Number of servers to start
- *
- * The given number of servers are started at first. Then
- * the given number of clients are configured to subscribe
- * all publishers. Then we wait for all servers
- * to terminate by theirself before we terminate the clients.
- *
- * This function is used by several tests for different setups.
- *
- * @note It is important to set up the publisher's
- * endpoint first. At least for inproc endpoints subscriber's
- * zmq_connect() will fail if the endpoint is not available.
- */
- static void doit(unsigned int clients, unsigned int servers) {
- void * zmqContext;
- THREAD_DATA_SERVER dataServers[SERVER_MAX];
- THREAD_DATA_CLIENT dataClients[CLIENT_MAX];
- int ret;
- unsigned int i;
- void *threadResult;
- assert(clients <= ARRAY_SIZE(dataClients));
- assert(servers <= ARRAY_SIZE(dataServers));
- /* Initialize */
- zmqContext = zmq_init(1);
- assert(zmqContext != NULL);
- /* Start clients */
- for (i = 0; i < clients; i += 1) {
- memset(&dataClients[i], 0, sizeof(dataClients[i]));
- dataClients[i].zmqContext = zmqContext;
- dataClients[i].threadIndex = i;
- dataClients[i].seqCount = COUNT_LOOPS;
- dataClients[i].publisherCount = servers;
- dataClients[i].bRun = TRUE;
- ret = pthread_create(&dataClients[i].threadId, NULL, threadClient, &dataClients[i]);
- assert(ret == 0);
- }
- /* Start servers */
- for (i = 0; i < servers; i += 1) {
- memset(&dataServers[i], 0, sizeof(dataServers[i]));
- dataServers[i].zmqContext = zmqContext;
- dataServers[i].threadIndex = i;
- dataServers[i].loopCount = COUNT_LOOPS;
- dataServers[i].bRun = FALSE;
- ret = pthread_create(&dataServers[i].threadId, NULL, threadServer, &dataServers[i]);
- assert(ret == 0);
- }
- /* Give clients time to initialize */
- ret = microsleep (CLIENT_STARTUP_MICROSECS);
- assert(ret == 0);
- /* Run servers */
- for (i = 0; i < servers; i += 1) {
- dataServers[i].bRun = TRUE;
- }
- /* Wait for servers */
- for (i = 0; i < servers; i += 1) {
- ret = pthread_join(dataServers[i].threadId, &threadResult);
- assert(ret == 0);
- assert(threadResult == NULL);
- }
- /* Stop clients */
- for (i = 0; i < clients; i += 1) {
- dataClients[i].bRun = FALSE;
- }
- for (i = 0; i < clients; i += 1) {
- ret = pthread_join(dataClients[i].threadId, &threadResult);
- assert(ret == 0);
- assert(threadResult == NULL);
- }
- /* Cleanup */
- ret = zmq_term(zmqContext);
- assert(ret == 0);
- }
- /**
- * Test case for 1 client and 1 server.
- */
- static void test1to1(void) {
- doit(1, 1);
- }
- /**
- * Test case for 1 client and SERVER_MAX servers.
- * @see SERVER_MAX
- */
- static void test1toN(void) {
- doit(1, SERVER_MAX);
- }
- /**
- * Test case for CLIENT_MAX clients and 1 server.
- * @see CLIENT_MAX
- */
- static void testNto1(void) {
- doit(CLIENT_MAX, 1);
- }
- /**
- * Test case for CLIENT_MAX clients and SERVER_MAX servers.
- * @see CLIENT_MAX
- * @see SERVER_MAX
- */
- static void testNtoN(void) {
- doit(CLIENT_MAX, SERVER_MAX);
- }
- /***********************************************************
- * FUNCTIONS
- ***********************************************************/
- /**
- * Application entry point.
- * @param argc Number of command line entries
- * @param argv List of command line entriy strings
- */
- int main(int argc, char* argv[])
- {
- DPRINTF("### test1to1 ###\n");
- test1to1();
- DPRINTF("### test1toN ###\n");
- test1toN();
- DPRINTF("### testNto1 ###\n");
- testNto1();
- DPRINTF("### testNtoN ###\n");
- testNtoN();
- DPRINTF("### Asserts failed: %d ###\n", errors);
- }
- /***********************************************************
- * END OF FILE
- ***********************************************************/
Advertisement
Add Comment
Please, Sign In to add comment