wangzhengquan
2021-02-01 dd0714b75b2e29087e3cd1184995bf38a453d833
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#include "shm_socket.h"
#include "hashtable.h"
#include "logger_factory.h"
#include <map>
#include <cassert>
#include "bus_error.h"
 
static Logger *logger = LoggerFactory::getLogger();
 
 
 
static void print_msg(char *head, shm_msg_t &msg) {
  // err_msg(0, "%s: key=%d, type=%d\n", head, msg.key, msg.type);
}
 
static pthread_once_t _once_ = PTHREAD_ONCE_INIT;
static pthread_key_t _perthread_socket_key_;
 
 
 
 
 
static void _destrory_socket_perthread(void *tmp_socket);
static void _create_socket_key_perthread(void);
 
// 检查key是否已经被使用,是返回0, 否返回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 LockFreeQueue<shm_msg_t> * shm_socket_bind_queue(int key, bool force) {
  hashtable_t *hashtable = mm_get_hashtable();
  LockFreeQueue<shm_msg_t> *queue;
  hashtable_lock(hashtable);
  void *tmp_ptr = hashtable_get(hashtable, key);
 
 
  if (tmp_ptr == NULL || tmp_ptr == (void *)1  ) {
    queue = new LockFreeQueue<shm_msg_t>(16);
    hashtable_put(hashtable, key, (void *)queue);
    hashtable_unlock(hashtable);
    return queue;
  } else if(force) {
    hashtable_unlock(hashtable);
    return (LockFreeQueue<shm_msg_t> *) queue;
  }
  
  hashtable_unlock(hashtable);
  return NULL;
}
 
/**
 * 绑定key到队列,但是并不会创建队列。
 */
static LockFreeQueue<shm_msg_t> * shm_socket_attach_queue(int key) {
  LockFreeQueue<shm_msg_t> * queue;
  hashtable_t *hashtable = mm_get_hashtable();
  void *tmp_ptr = hashtable_get(hashtable, key);
  if (tmp_ptr == NULL || tmp_ptr == (void *)1) {
    //logger->error("shm_socket._remote_queue_attach:connet at key %d  failed!", key);
    return NULL;
  }
 
  queue = ( LockFreeQueue<shm_msg_t> *)tmp_ptr;
  // hashtable_unlock(hashtable);
  return queue;
}
 
 
size_t shm_socket_remove_keys(int keys[], size_t length) {
  hashtable_t *hashtable = mm_get_hashtable();
  LockFreeQueue<shm_msg_t> *mqueue;
  size_t count = 0;
  for(int i = 0; i< length; i++) {
    // 销毁共享内存的queue
    mqueue = (LockFreeQueue<shm_msg_t> *)hashtable_get(hashtable, keys[i]);
    delete mqueue;
    hashtable_remove(hashtable, keys[i]);
    count++;
  }
  return count;
}
 
shm_socket_t *shm_open_socket(shm_socket_type_t socket_type) {
  int s, type;
  pthread_mutexattr_t mtxAttr;
 
  logger->debug("shm_open_socket\n");
  shm_socket_t *socket = (shm_socket_t *)calloc(1, sizeof(shm_socket_t));
  socket->socket_type = socket_type;
  socket->key = 0;
  socket->force_bind = false;
  socket->queue = NULL;
 
 
  s = pthread_mutexattr_init(&mtxAttr);
  if (s != 0)
    err_exit(s, "pthread_mutexattr_init");
  s = pthread_mutexattr_settype(&mtxAttr, PTHREAD_MUTEX_ERRORCHECK);
  if (s != 0)
    err_exit(s, "pthread_mutexattr_settype");
  s = pthread_mutex_init(&(socket->mutex), &mtxAttr);
  if (s != 0)
    err_exit(s, "pthread_mutex_init");
 
  s = pthread_mutexattr_destroy(&mtxAttr);
  if (s != 0)
    err_exit(s, "pthread_mutexattr_destroy");
 
  return socket;
}
 
int shm_close_socket(shm_socket_t *socket) {
  
  int s;
  
  logger->debug("shm_close_socket\n");
  if(socket->queue != NULL) {
    delete socket->queue;
    socket->queue = NULL;
  }
 
  s =  pthread_mutex_destroy(&(socket->mutex) );
  if(s != 0) {
    err_exit(s, "shm_close_socket");
  }
 
  free(socket);
  return 0;
}
 
// int shm_close_socket(shm_socket_t *socket) {
  
//   // _destrory_socket_perthread((shm_socket_t *)pthread_getspecific(_perthread_socket_key_));
 
//   return shm_close_socket(socket);;
// }
 
int shm_socket_bind(shm_socket_t *socket, int key) {
  socket->key = key;
  return 0;
}
 
int shm_socket_force_bind(shm_socket_t *socket, int key) {
  socket->force_bind = true;
  socket->key = key;
  return 0;
}
 
int shm_socket_get_key(shm_socket_t *sk){
  return sk->key;
}
 
  
 
 
// 短连接方式发送
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;
  int rv;
 
  hashtable_t *hashtable = mm_get_hashtable();
 
 
  if ((s = pthread_mutex_lock(&(sockt->mutex))) != 0)
    err_exit(s, "shm_sendto : pthread_mutex_lock");
 
  if (sockt->queue == NULL) {
    if (sockt->key == 0) {
      sockt->key = hashtable_alloc_key(hashtable);
    }
    sockt->queue = shm_socket_bind_queue( sockt->key, sockt->force_bind);
    if(sockt->queue  == NULL ) {
      logger->error("%s. key = %d", bus_strerror(EBUS_KEY_INUSED), sockt->key);
      return EBUS_KEY_INUSED;
    }
  }
 
  if ((s = pthread_mutex_unlock(&(sockt->mutex))) != 0)
    err_exit(s, "shm_sendto : pthread_mutex_unlock");
  
  // 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;
  }
 
  LockFreeQueue<shm_msg_t> *remoteQueue;
  if ((remoteQueue = shm_socket_attach_queue(key)) == NULL) {
    bus_errno = EBUS_CLOSED;
    logger->error("sendto key %d failed, %s", key, bus_strerror(bus_errno));
    return EBUS_CLOSED;
  }
 
  shm_msg_t dest;
  dest.type = SHM_COMMON_MSG;
  dest.key = sockt->key;
  dest.size = size;
  dest.buf = mm_malloc(size);
  memcpy(dest.buf, buf, size);
 
  rv = remoteQueue->push(dest, timeout, flag);
 
  if (rv == 0) {
    printf("%d sendto %d suc.\n", shm_socket_get_key(sockt), key);
    return 0;
  } else {
    mm_free(dest.buf);
    if(rv == ETIMEDOUT)
      return EBUS_TIMEOUT;
    else {
      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 *sockt, void **buf, int *size, int *key,  const struct timespec *timeout,  int flag) {
  int s;
  int rv;
 
  
  hashtable_t *hashtable = mm_get_hashtable();
 
  if ((s = pthread_mutex_lock(&(sockt->mutex))) != 0)
    err_exit(s, "shm_recvfrom : pthread_mutex_lock");
 
  if (sockt->queue == NULL) {
    if (sockt->key == 0) {
      sockt->key = hashtable_alloc_key(hashtable);
    }  
    sockt->queue = shm_socket_bind_queue( sockt->key, sockt->force_bind);
    if(sockt->queue  == NULL ) {
      logger->error("%s. key = %d", bus_strerror(EBUS_KEY_INUSED), sockt->key);
      return EBUS_KEY_INUSED;
    }
  }
  
  if ((s = pthread_mutex_unlock(&(sockt->mutex))) != 0)
    err_exit(s, "shm_recvfrom : pthread_mutex_unlock");
 
  shm_msg_t src;
 
  rv = sockt->queue->pop(src, timeout, flag);
 
  if (rv == 0) {
    if(buf != NULL) {
      void *_buf = malloc(src.size);
      memcpy(_buf, src.buf, src.size);
      *buf = _buf; 
    }
   
    if(size != NULL)
      *size = src.size;
 
    if(key != NULL)
      *key = src.key;
 
    mm_free(src.buf);
    return 0;
  } else {
    if(rv == ETIMEDOUT)
      return EBUS_TIMEOUT;
    else {
      logger->debug("%d shm_recvfrom failed %s", shm_socket_get_key(sockt), bus_strerror(rv));
      return rv;
    }
   
 
  }
}
 
 
 /* Free thread-specific data buffer */
static void _destrory_socket_perthread(void *tmp_socket)
{
  int rv;
  if(tmp_socket == NULL)
    return;
 
  logger->debug("%d destroy tmp socket\n", pthread_self()); 
  shm_close_socket((shm_socket_t *)tmp_socket);
  rv =  pthread_setspecific(_perthread_socket_key_, NULL);
  if ( rv != 0) {
    logger->error(rv, "shm_sendandrecv : pthread_setspecific");
    exit(1);
  }
}
 
/* One-time key creation function */
static void _create_socket_key_perthread(void)
{
  int s;
 
  /* Allocate a unique thread-specific data key and save the address
     of the destructor for thread-specific data buffers */
  s = pthread_key_create(&_perthread_socket_key_, _destrory_socket_perthread);
  //s = pthread_key_create(&_perthread_socket_key_, NULL);
  if (s != 0) {
     logger->error(s, "pthread_key_create");
     abort(); /* dump core and terminate */ 
     exit(1);
  }
}
 
 
// use thread local
int _shm_sendandrecv_thread_local(shm_socket_t *sockt, const void *send_buf,
                    const int send_size, const int send_key, void **recv_buf,
                    int *recv_size,  const struct timespec *timeout,  int flags) {
  int recv_key;
  int rv;
 
  // 用thread local 保证每个线程用一个独占的socket接受对方返回的信息
  shm_socket_t *tmp_socket;
 
 
  rv = pthread_once(&_once_, _create_socket_key_perthread);
  if (rv != 0) {
    logger->error(rv, "shm_sendandrecv pthread_once");
    exit(1);
  }
 
  tmp_socket = (shm_socket_t *)pthread_getspecific(_perthread_socket_key_);
  if (tmp_socket == NULL)
  {
    /* If first call from this thread, allocate buffer for thread, and save its location */
    logger->debug("%ld create tmp socket\n", (long)pthread_self() );
    tmp_socket = shm_open_socket(SHM_SOCKET_DGRAM);
 
    rv =  pthread_setspecific(_perthread_socket_key_, tmp_socket);
    if ( rv != 0) {
      logger->error(rv, "shm_sendandrecv : pthread_setspecific");
      exit(1);
    }
  }
 
  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) {
      logger->error("_shm_sendandrecv_thread_local : %s\n", bus_strerror(rv));
    }
    else if(rv == 0 ) {
      logger->debug("======%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(recv_key == shm_socket_get_key(sockt)) {
        logger->debug("=====收到了自己发给自己的消息\n");
      }
      assert( send_key == recv_key);
      if(send_key != recv_key) {
        logger->error( "_shm_sendandrecv_alloc_new: send key expect to equal to recv key! send key =%d , recv key=%d", send_key, recv_key);
        exit(1);
      }
    }
    return rv;
  } else {
    return rv;
  }
}
 
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,  const struct timespec *timeout,  int flags) {
  int recv_key;
  int rv;
 
  // 用thread local 保证每个线程用一个独占的socket接受对方返回的信息
  shm_socket_t *tmp_socket;
 
  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 ",
             sockt->socket_type);
    exit(1);
  }
 
  /* If first call from this thread, allocate buffer for thread, and save its location */
  // logger->debug("%d create tmp socket\n", pthread_self() );
  tmp_socket = shm_open_socket(SHM_SOCKET_DGRAM);
 
  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_alloc_new : %s\n", bus_strerror(rv));
    }
    else if(rv == 0 ) {
      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(recv_key == shm_socket_get_key(sockt)) {
        printf("=====收到了自己发给自己的消息\n");
      }
      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(shm_socket_t *socket, const void *send_buf,
                    const int send_size, const int send_key, void **recv_buf,
                    int *recv_size,  const struct timespec *timeout,  int flags) {
 
  return  _shm_sendandrecv_thread_local(socket, send_buf, send_size, send_key,recv_buf, recv_size, timeout,  flags);
}
 
 
// ============================================================================================================