wangzhengquan
2021-01-30 f2a03c696bcf76bbaba349325abeef7be3979205
src/socket/shm_socket.cpp
@@ -2,6 +2,7 @@
#include "hashtable.h"
#include "logger_factory.h"
#include <map>
#include <cassert>
#include "bus_error.h"
static Logger *logger = LoggerFactory::getLogger();
@@ -27,14 +28,28 @@
static void _create_tmp_recv_socket_key(void);
// 检查key是否已经被使用,是返回0, 否返回1
static inline int  _shm_socket_check_key(shm_socket_t *socket) {
   void *tmp_ptr = mm_get_by_key(socket->key);
    if (tmp_ptr!= NULL && tmp_ptr != (void *)1 && !socket->force_bind ) {
      bus_errno = ESHM_BUS_KEY_INUSED;
      logger->error("%s. key = %d ", bus_strerror(bus_errno), socket->key);
      return 0;
    }
    return 1;
// static  int  _shm_socket_check_key(shm_socket_t *socket) {
//    void *tmp_ptr = mm_get_by_key(socket->key);
//     if (tmp_ptr!= NULL && tmp_ptr != (void *)1 && !socket->force_bind ) {
//       bus_errno = EBUS_KEY_INUSED;
//       logger->error("%s. key = %d ", bus_strerror(EBUS_KEY_INUSED), socket->key);
//       return 0;
//     }
//     return 1;
// }
//  检查key是否已经被使用, 未被使用则绑定key
static int check_and_bind_queue(shm_socket_t * sockt) {
  hashtable_t *hashtable = mm_get_hashtable();
  hashtable_lock(hashtable);
  void *tmp_ptr = mm_get_by_key(sockt->key);
  if (tmp_ptr!= NULL && tmp_ptr != (void *)1 && !sockt->force_bind ) {
    hashtable_unlock(hashtable);
    return EBUS_KEY_INUSED;
  }
  sockt->queue = new SHMQueue<shm_msg_t>(sockt->key, 16);
  hashtable_unlock(hashtable);
  return 0;
}
SHMQueue<shm_msg_t> *_attach_remote_queue(int key);
@@ -117,9 +132,13 @@
  return 0;
}
int shm_listen(shm_socket_t *socket) {
int shm_socket_get_key(shm_socket_t *sk){
  return sk->key;
}
  if (socket->socket_type != SHM_SOCKET_STREAM) {
int shm_listen(shm_socket_t *sockt) {
  int rv;
  if (sockt->socket_type != SHM_SOCKET_STREAM) {
    logger->error("can not invoke shm_listen method with a socket which is not a "
                "SHM_SOCKET_STREAM socket");
    exit(1);
@@ -127,23 +146,23 @@
  int key;
  hashtable_t *hashtable = mm_get_hashtable();
  if (socket->key == 0) {
  if (sockt->key == 0) {
    key = hashtable_alloc_key(hashtable);
    socket->key = key;
    sockt->key = key;
  } else {
   if(!_shm_socket_check_key(socket)) {
     bus_errno = ESHM_BUS_KEY_INUSED;
     return ESHM_BUS_KEY_INUSED;
   }
    rv = check_and_bind_queue(sockt);
    if(rv !=0 ) {
      return rv;
    }
  }
  socket->queue = new SHMQueue<shm_msg_t>(socket->key, 16);
  socket->acceptQueue = new LockFreeQueue<shm_msg_t, DM_Allocator>(16);
  socket->clientSocketMap = new std::map<int, shm_socket_t *>;
  socket->status = SHM_CONN_LISTEN;
  pthread_create(&(socket->dispatch_thread), NULL, _server_run_msg_rev,
                 (void *)socket);
  sockt->queue = new SHMQueue<shm_msg_t>(sockt->key, 16);
  sockt->acceptQueue = new LockFreeQueue<shm_msg_t, DM_Allocator>(16);
  sockt->clientSocketMap = new std::map<int, shm_socket_t *>;
  sockt->status = SHM_CONN_LISTEN;
  pthread_create(&(sockt->dispatch_thread), NULL, _server_run_msg_rev,
                 (void *)sockt);
  return 0;
}
@@ -152,8 +171,8 @@
 * 接受客户端建立新连接的请求
 *
*/
shm_socket_t *shm_accept(shm_socket_t *socket) {
  if (socket->socket_type != SHM_SOCKET_STREAM) {
shm_socket_t *shm_accept(shm_socket_t *sockt) {
  if (sockt->socket_type != SHM_SOCKET_STREAM) {
    logger->error("can not invoke shm_accept method with a socket which is not a "
                "SHM_SOCKET_STREAM socket");
    exit(1);
@@ -163,13 +182,13 @@
  shm_socket_t *client_socket;
  shm_msg_t src;
  if (socket->acceptQueue->pop(src) == 0) {
  if (sockt->acceptQueue->pop(src) == 0) {
    // print_msg("===accept:", src);
    client_key = src.key;
    // client_socket = (shm_socket_t *)malloc(sizeof(shm_socket_t));
    client_socket = shm_open_socket(socket->socket_type);
    client_socket->key = socket->key;
    client_socket = shm_open_socket(sockt->socket_type);
    client_socket->key = sockt->key;
    // client_socket->queue= socket->queue;
    //初始化消息queue
    client_socket->messageQueue =
@@ -177,7 +196,7 @@
    //连接到对方queue
    client_socket->remoteQueue = _attach_remote_queue(client_key);
    socket->clientSocketMap->insert({client_key, client_socket});
    sockt->clientSocketMap->insert({client_key, client_socket});
    /*
* shm_accept 用户执行的方法
@@ -186,11 +205,11 @@
    //发送open_reply,回应客户端的connect请求
    struct timespec timeout = {1, 0};
    shm_msg_t msg;
    msg.key = socket->key;
    msg.key = sockt->key;
    msg.size = 0;
    msg.type = SHM_SOCKET_OPEN_REPLY;
    if (client_socket->remoteQueue->push_timeout(msg, &timeout) == 0) {
    if (client_socket->remoteQueue->push(msg, &timeout, BUS_TIMEOUT_FLAG) == 0) {
      client_socket->status = SHM_CONN_ESTABLISHED;
      return client_socket;
    } else {
@@ -208,8 +227,9 @@
/**
 * @return 0成功. 其他值失败
 */
int shm_connect(shm_socket_t *socket, int key) {
  if (socket->socket_type != SHM_SOCKET_STREAM) {
int shm_connect(shm_socket_t *sockt, int key) {
  int rv;
  if (sockt->socket_type != SHM_SOCKET_STREAM) {
    logger->error( "can not invoke shm_connect method with a socket which is not "
                "a SHM_SOCKET_STREAM socket");
    exit(1);
@@ -220,38 +240,37 @@
    return -1;
  }
  if (socket->key == 0) {
    socket->key = hashtable_alloc_key(hashtable);
  if (sockt->key == 0) {
    sockt->key = hashtable_alloc_key(hashtable);
    sockt->queue = new SHMQueue<shm_msg_t>(sockt->key, 16);
  } else {
    if(!_shm_socket_check_key(socket)) {
      bus_errno = ESHM_BUS_KEY_INUSED;
      return ESHM_BUS_KEY_INUSED;
    rv = check_and_bind_queue(sockt);
    if(rv != 0 ) {
      return rv;
    }
  }
  socket->queue = new SHMQueue<shm_msg_t>(socket->key, 16);
  if ((socket->remoteQueue = _attach_remote_queue(key)) == NULL) {
  if ((sockt->remoteQueue = _attach_remote_queue(key)) == NULL) {
    logger->error("connect to %d failted", key);
    return -1;
  }
  socket->messageQueue = new LockFreeQueue<shm_msg_t, DM_Allocator>(16);
  sockt->messageQueue = new LockFreeQueue<shm_msg_t, DM_Allocator>(16);
  //发送open请求
  struct timespec timeout = {1, 0};
  shm_msg_t msg;
  msg.key = socket->key;
  msg.key = sockt->key;
  msg.size = 0;
  msg.type = SHM_SOCKET_OPEN;
  socket->remoteQueue->push_timeout(msg, &timeout);
  sockt->remoteQueue->push(msg, &timeout, BUS_TIMEOUT_FLAG);
  //接受open reply
  if (socket->queue->pop(msg) == 0) {
  if (sockt->queue->pop(msg) == 0) {
    // 在这里server端已经准备好接受客户端发送请求了,完成与服务端的连接
    if (msg.type == SHM_SOCKET_OPEN_REPLY) {
      socket->status = SHM_CONN_ESTABLISHED;
      pthread_create(&(socket->dispatch_thread), NULL, _client_run_msg_rev,
                     (void *)socket);
      sockt->status = SHM_CONN_ESTABLISHED;
      pthread_create(&(sockt->dispatch_thread), NULL, _client_run_msg_rev,
                     (void *)sockt);
    } else {
      logger->error( "shm_connect: 不匹配的应答信息!");
      exit(1);
@@ -265,25 +284,25 @@
  return 0;
}
int shm_send(shm_socket_t *socket, const void *buf, const int size) {
  if (socket->socket_type != SHM_SOCKET_STREAM) {
int shm_send(shm_socket_t *sockt, const void *buf, const int size) {
  if (sockt->socket_type != SHM_SOCKET_STREAM) {
    logger->error("shm_socket.shm_send: can not invoke shm_send method with a socket which is not a "
                "SHM_SOCKET_STREAM socket");
    exit(1);
  }
  hashtable_t *hashtable = mm_get_hashtable();
  if(socket->remoteQueue == NULL) {
  if(sockt->remoteQueue == NULL) {
     err_msg(errno, "当前客户端无连接!");
     return -1;
  }
  shm_msg_t dest;
  dest.type = SHM_COMMON_MSG;
  dest.key = socket->key;
  dest.key = sockt->key;
  dest.size = size;
  dest.buf = mm_malloc(size);
  memcpy(dest.buf, buf, size);
  if (socket->remoteQueue->push(dest) == 0) {
  if (sockt->remoteQueue->push(dest) == 0) {
    return 0;
  } else {
    logger->error(errno, "connection has been closed!");
@@ -291,16 +310,16 @@
  }
}
int shm_recv(shm_socket_t *socket, void **buf, int *size) {
  if (socket->socket_type != SHM_SOCKET_STREAM) {
int shm_recv(shm_socket_t *sockt, void **buf, int *size) {
  if (sockt->socket_type != SHM_SOCKET_STREAM) {
    logger->error( "shm_socket.shm_recv: can not invoke shm_recv method in a %d type socket  which is "
                "not a SHM_SOCKET_STREAM socket ",
             socket->socket_type);
             sockt->socket_type);
    exit(1);
  }
  shm_msg_t src;
  if (socket->messageQueue->pop(src) == 0) {
  if (sockt->messageQueue->pop(src) == 0) {
    void *_buf = malloc(src.size);
    memcpy(_buf, src.buf, src.size);
    *buf = _buf;
@@ -314,46 +333,48 @@
// 短连接方式发送
int shm_sendto(shm_socket_t *socket, const void *buf, const int size,
               const int key, const struct timespec *timeout, const int flags) {
int shm_sendto(shm_socket_t *sockt, const void *buf, const int size,
               const int key, const struct timespec *timeout, const int flag) {
  int s;
  bool rv;
  int rv;
  if (socket->socket_type != SHM_SOCKET_DGRAM) {
  if (sockt->socket_type != SHM_SOCKET_DGRAM) {
    logger->error( "shm_socket.shm_sendto: Can't invoke shm_sendto method in a %d type socket  which is "
                "not a SHM_SOCKET_DGRAM socket ",
             socket->socket_type);
             sockt->socket_type);
    exit(0);
  }
  hashtable_t *hashtable = mm_get_hashtable();
 
  if ((s = pthread_mutex_lock(&(socket->mutex))) != 0)
  if ((s = pthread_mutex_lock(&(sockt->mutex))) != 0)
    err_exit(s, "shm_sendto : pthread_mutex_lock");
  if (socket->queue == NULL) {
    if (socket->key == 0) {
      socket->key = hashtable_alloc_key(hashtable);
  if (sockt->queue == NULL) {
    if (sockt->key == 0) {
      sockt->key = hashtable_alloc_key(hashtable);
      sockt->queue = new SHMQueue<shm_msg_t>(sockt->key, 16);
    } else {
     if(!_shm_socket_check_key(socket)) {
        bus_errno = ESHM_BUS_KEY_INUSED;
        return ESHM_BUS_KEY_INUSED;
     }
      rv = check_and_bind_queue(sockt);
      if(rv !=0 ) {
        return rv;
      }
    }
    socket->queue = new SHMQueue<shm_msg_t>(socket->key, 16);
  }
  if ((s = pthread_mutex_unlock(&(socket->mutex))) != 0)
  if ((s = pthread_mutex_unlock(&(sockt->mutex))) != 0)
    err_exit(s, "shm_sendto : pthread_mutex_unlock");
  
  // if (key == socket->key) {
  //   logger->error( "can not send to your self!");
  //   return -1;
  // }
  // There is some case where a sockt need to send to himeself, for example when bus server need to stop, he need to send himself
  // a top message.
  if (key == sockt->key) {
    logger->error( "can not send to your self!");
    return EBUS_SENDTO_SELF;
  }
  SHMQueue<shm_msg_t> *remoteQueue;
  if ((remoteQueue = _attach_remote_queue(key)) == NULL) {
@@ -364,82 +385,58 @@
  shm_msg_t dest;
  dest.type = SHM_COMMON_MSG;
  dest.key = socket->key;
  dest.key = sockt->key;
  dest.size = size;
  dest.buf = mm_malloc(size);
  memcpy(dest.buf, buf, size);
  if(flags & SHM_MSG_NOWAIT != 0) {
    rv = remoteQueue->push_nowait(dest);
  } else if(timeout != NULL) {
     rv = remoteQueue->push_timeout(dest, timeout);
  } else {
     rv = remoteQueue->push(dest);
  }
  rv = remoteQueue->push(dest, timeout, flag);
  if (rv == 0) {
    // printf("shm_sendto push after\n");
    delete remoteQueue;
    printf("%d sendto %d suc.\n", shm_socket_get_key(sockt), key);
    return 0;
  } else {
    delete remoteQueue;
    mm_free(dest.buf);
    if(rv == EBUS_TIMEOUT) {
      // bus_errno = EBUS_TIMEOUT;
      // logger->error("sendto key %d failed, %s", key, bus_strerror(EBUS_TIMEOUT));
      return EBUS_TIMEOUT;
    } else {
      //logger->error(errno, "sendto key %d failed!", key);
      return rv;
    }
    logger->debug("%d sendto key %d failed %s", shm_socket_get_key(sockt), key, bus_strerror(rv));
    return rv;
  }
}
// 短连接方式接受
int shm_recvfrom(shm_socket_t *socket, void **buf, int *size, int *key,  struct timespec *timeout,  int flags) {
  int s;
  bool rv;
  if (socket->socket_type != SHM_SOCKET_DGRAM) {
// 短连接方式接受
int shm_recvfrom(shm_socket_t *sokt, void **buf, int *size, int *key,  const struct timespec *timeout,  int flag) {
  int s;
  int rv;
  if (sokt->socket_type != SHM_SOCKET_DGRAM) {
    logger->error("shm_socket.shm_recvfrom: Can't invoke shm_recvfrom method in a %d type socket  which "
                "is not a SHM_SOCKET_DGRAM socket ",
             socket->socket_type);
             sokt->socket_type);
    exit(1);
  }
  hashtable_t *hashtable = mm_get_hashtable();
  if ((s = pthread_mutex_lock(&(socket->mutex))) != 0)
  if ((s = pthread_mutex_lock(&(sokt->mutex))) != 0)
    err_exit(s, "shm_recvfrom : pthread_mutex_lock");
 
  if (socket->queue == NULL) {
    if (socket->key == 0) {
      socket->key = hashtable_alloc_key(hashtable);
  if (sokt->queue == NULL) {
    if (sokt->key == 0) {
      sokt->key = hashtable_alloc_key(hashtable);
      sokt->queue = new SHMQueue<shm_msg_t>(sokt->key, 16);
    } else {
      if(!_shm_socket_check_key(socket)) {
        bus_errno = ESHM_BUS_KEY_INUSED;
        return ESHM_BUS_KEY_INUSED;
      rv = check_and_bind_queue(sokt);
      if(rv != 0 ) {
        return rv;
      }
    }
    socket->queue = new SHMQueue<shm_msg_t>(socket->key, 16);
  }
  
  if ((s = pthread_mutex_unlock(&(socket->mutex))) != 0)
  if ((s = pthread_mutex_unlock(&(sokt->mutex))) != 0)
    err_exit(s, "shm_recvfrom : pthread_mutex_unlock");
  shm_msg_t src;
 
   if(flags & SHM_MSG_NOWAIT != 0) {
    rv = socket->queue->pop_nowait(src);
  } else if(timeout != NULL) {
    rv = socket->queue->pop_timeout(src, timeout);
  } else {
    rv = socket->queue->pop(src);
  }
  rv = sokt->queue->pop(src, timeout, flag);
  if (rv == 0) {
    if(buf != NULL) {
@@ -457,14 +454,8 @@
    mm_free(src.buf);
    return 0;
  } else {
    if(rv == EBUS_TIMEOUT) {
      // logger->error("shm_recvfrom  failed, %s", bus_strerror(EBUS_TIMEOUT));
      return EBUS_TIMEOUT;
    } else {
      // logger->error(rv, "shm_recvfrom  failed!");
      return rv;
    }
    logger->debug("shm_recvfrom failed %s", bus_strerror(rv));
    return rv;
  }
}
@@ -506,7 +497,7 @@
// use thread local
int _shm_sendandrecv_thread_local(shm_socket_t *socket, const void *send_buf,
                    const int send_size, const int send_key, void **recv_buf,
                    int *recv_size,  struct timespec *timeout,  int flags) {
                    int *recv_size,  const struct timespec *timeout,  int flags) {
  int recv_key;
  int rv;
@@ -531,7 +522,7 @@
  if (tmp_socket == NULL)
  {
    /* If first call from this thread, allocate buffer for thread, and save its location */
    logger->debug("%d create tmp socket\n", pthread_self() );
    logger->debug("%ld create tmp socket\n", (long)pthread_self() );
    tmp_socket = shm_open_socket(SHM_SOCKET_DGRAM);
    rv =  pthread_setspecific(_tmp_recv_socket_key_, tmp_socket);
@@ -543,28 +534,35 @@
  if ((rv = shm_sendto(tmp_socket, send_buf, send_size, send_key, timeout, flags)) == 0) {
    rv = shm_recvfrom(tmp_socket, recv_buf, recv_size, &recv_key, timeout, flags);
    if(rv != 0) {
      printf("_shm_sendandrecv_thread_local : %s\n", bus_strerror(rv));
    }
    else if(rv == 0 ) {
      assert( send_key == recv_key);
      if(send_key != recv_key) {
         err_exit(0, "_shm_sendandrecv_thread_local: send key expect to equal to recv key! send key =%d , recv key=%d", send_key, recv_key);
      }
    }
    return rv;
  } else {
    return rv;
  }
  return -1;
}
int _shm_sendandrecv_alloc_new(shm_socket_t *socket, const void *send_buf,
int _shm_sendandrecv_alloc_new(shm_socket_t *sockt, const void *send_buf,
                    const int send_size, const int send_key, void **recv_buf,
                    int *recv_size,  struct timespec *timeout,  int flags) {
                    int *recv_size,  const struct timespec *timeout,  int flags) {
  int recv_key;
  int rv;
  // 用thread local 保证每个线程用一个独占的socket接受对方返回的信息
  shm_socket_t *tmp_socket;
  if (socket->socket_type != SHM_SOCKET_DGRAM) {
  if (sockt->socket_type != SHM_SOCKET_DGRAM) {
    logger->error( "shm_socket.shm_sendandrecv: Can't invoke shm_sendandrecv method in a %d type socket  "
                "which is not a SHM_SOCKET_DGRAM socket ",
             socket->socket_type);
             sockt->socket_type);
    exit(1);
  }
 
@@ -574,39 +572,30 @@
  if ((rv = shm_sendto(tmp_socket, send_buf, send_size, send_key, timeout, flags)) == 0) {
    rv = shm_recvfrom(tmp_socket, recv_buf, recv_size, &recv_key, timeout, flags);
    printf("======%d use tmp_socket %d, send to  %d, receive from  %d\n", shm_socket_get_key(sockt), shm_socket_get_key(tmp_socket), send_key, recv_key);
    if(rv != 0) {
      printf("_shm_sendandrecv_alloc_new : %s\n", bus_strerror(rv));
    }
    else if(rv == 0 ) {
      assert( send_key == recv_key);
      if(send_key != recv_key) {
         err_exit(0, "_shm_sendandrecv_alloc_new: send key expect to equal to recv key! send key =%d , recv key=%d", send_key, recv_key);
      }
    }
  } 
   
  shm_close_socket(tmp_socket);  
  return rv;
 
}
int shm_sendandrecv_unsafe(shm_socket_t *socket, const void *send_buf,
                    const int send_size, const int send_key, void **recv_buf,
                    int *recv_size,  struct timespec *timeout,  int flags) {
  if (socket->socket_type != SHM_SOCKET_DGRAM) {
    logger->error( "shm_socket.shm_sendandrecv_unsafe : Can't invoke shm_sendandrecv method in a %d type socket  "
                "which is not a SHM_SOCKET_DGRAM socket ",
             socket->socket_type);
    exit(1);
  }
  int recv_key;
  int rv;
 
  if ((rv = shm_sendto(socket, send_buf, send_size, send_key, timeout, flags)) == 0) {
    rv = shm_recvfrom(socket, recv_buf, recv_size, &recv_key, timeout, flags);
    return rv;
  } else {
    return rv;
  }
  return -1;
}
int shm_sendandrecv(shm_socket_t *socket, const void *send_buf,
                    const int send_size, const int send_key, void **recv_buf,
                    int *recv_size,  struct timespec *timeout,  int flags) {
  return  _shm_sendandrecv_thread_local(socket, send_buf, send_size, send_key,recv_buf, recv_size, timeout,  flags);
                    int *recv_size,  const struct timespec *timeout,  int flags) {
  return  _shm_sendandrecv_alloc_new(socket, send_buf, send_size, send_key,recv_buf, recv_size, timeout,  flags);
}
@@ -653,7 +642,7 @@
    switch (src.type) {
    case SHM_SOCKET_OPEN:
      socket->acceptQueue->push_timeout(src, &timeout);
      socket->acceptQueue->push(src, &timeout, BUS_TIMEOUT_FLAG);
      break;
    case SHM_SOCKET_CLOSE:
      _server_close_conn_to_client(socket, src.key);
@@ -664,7 +653,7 @@
      if (iter != socket->clientSocketMap->end()) {
        client_socket = iter->second;
        // print_msg("_server_run_msg_rev push before", src);
        client_socket->messageQueue->push_timeout(src, &timeout);
        client_socket->messageQueue->push(src, &timeout, BUS_TIMEOUT_FLAG);
        // print_msg("_server_run_msg_rev push after", src);
      }
@@ -699,7 +688,7 @@
      _client_close_conn_to_server(socket);
      break;
    case SHM_COMMON_MSG:
      socket->messageQueue->push_timeout(src, &timeout);
      socket->messageQueue->push(src, &timeout, BUS_TIMEOUT_FLAG);
      break;
    default:
       logger->error( "shm_socket._client_run_msg_rev: undefined message type.");
@@ -719,7 +708,7 @@
  close_msg.size = 0;
  close_msg.type = SHM_SOCKET_CLOSE;
  if (notifyRemote && socket->remoteQueue != NULL) {
    socket->remoteQueue->push_timeout(close_msg, &timeout);
    socket->remoteQueue->push(close_msg, &timeout, BUS_TIMEOUT_FLAG);
  }
  if (socket->queue != NULL) {
@@ -727,10 +716,7 @@
    socket->queue = NULL;
  }
  if (socket->remoteQueue != NULL) {
    delete socket->remoteQueue;
    socket->remoteQueue = NULL;
  }
  if (socket->messageQueue != NULL) {
    delete socket->messageQueue;
@@ -748,8 +734,7 @@
         iter != socket->clientSocketMap->end(); iter++) {
      client_socket = iter->second;
      client_socket->remoteQueue->push_timeout(close_msg, &timeout);
      delete client_socket->remoteQueue;
      client_socket->remoteQueue->push(close_msg, &timeout, BUS_TIMEOUT_FLAG);
      client_socket->remoteQueue = NULL;
      delete client_socket->messageQueue;