fujuntang
2021-12-09 73689afc09ce346f9eb00e02faf7f242e55dc7ee
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
#include <assert.h>
#include "net_mod_server_socket_wrapper.h"
#include "net_mod_socket_wrapper.h"
#include "bus_server_socket_wrapper.h"
 
#include "shm_mm_wrapper.h"
#include "usg_common.h"
#include <getopt.h>
#include "logger_factory.h"
 
#define  SCALE  100000
 
static Logger *logger = LoggerFactory::getLogger();
 
typedef struct Targ {
  net_node_t *node;
    char *nodelist;
    long id;
 
}Targ;
 
struct argument_t {
  bool interactive;
  bool force;
  int bind;
  int port;
  int key;
  char *sendlist;
  char *publist;
  char **cmd_arr;
  int cmd_arr_len;
};
 
argument_t parse_args (int argc, char *argv[]);
void usage(char *name);
int parse_node_list(const char *str, net_node_t *node_arr_addr[]) ;
void print_node_list(net_node_t *node_arr, int len);
 
 
 
void * client;
 
void *proxy_server_handler(void *sockt) {
  pthread_detach(pthread_self());
  
  char action[512];
  while ( true ) {
    printf("Input action: Close?\n");
    if(scanf("%s",action) < 1) {
      printf("Invalide action\n");
      continue;
    }
 
    if(strcmp(action, "close") == 0) {
      net_mod_server_socket_close(sockt);
      shm_mm_wrapper_destroy();
      break;
    } else {
      printf("Invalide action\n");
    }
  }  
}
 
void start_net_proxy(argument_t &arg) {
  pthread_t tid;
  printf("Start net proxy\n");
    void *serverSocket  = net_mod_server_socket_open(arg.port);
 
   // 创建一个线程,可以关闭server
  if(arg.interactive) {
    pthread_create(&tid, NULL, proxy_server_handler, serverSocket);
  }
  
    if(net_mod_server_socket_start(serverSocket) != 0) {
        err_exit(errno, "net_mod_server_socket_start");
    }
}
 
void start_resycle() {
  shm_mm_wrapper_start_resycle();
}
 
 
// 打印接受到的订阅消息
void *print_sub_msg(void *sockt) {
  pthread_detach(pthread_self());
  void *recvbuf;
  int size;
  int key;
  int rv;
  while ((rv = net_mod_socket_recvfrom( sockt, &recvbuf, &size, &key) ) == 0) {
    printf("收到订阅消息:%s\n", (char *)recvbuf);
    free(recvbuf);
  }
 
  printf("print_sub_msg return . rv = %d\n", rv);
  
}
 
 
void * bus_server;
 
static void stop_bus_handler(int sig) {
  bus_server_socket_wrapper_stop(bus_server);
}
 
 
void start_bus_server(argument_t &arg) {
  printf("Start bus server\n");
  bus_server = bus_server_socket_wrapper_open();
  
  signal(SIGINT,  stop_bus_handler);
  signal(SIGTERM,  stop_bus_handler);
 
  if(bus_server_socket_wrapper_start_bus(bus_server) != 0) {
    printf("start bus failed\n");
    exit(1);
  }
 
  bus_server_socket_wrapper_close(bus_server);
}
 
void *serverSockt;
 
 
static void _recvandsend_callback_(void *recvbuf, int recvsize, int key, void **sendbuf_ptr, int *sendsize_ptr, void * user_data) {
  char sendbuf[512];
  printf( "server: RECEIVED REQUEST FROM  %d : %s\n", key, (char *)recvbuf);
  sprintf(sendbuf, "%d RECEIVED %s", net_mod_socket_get_key(serverSockt), (char *)recvbuf);
  // buf 和 size是返回值
  *sendbuf_ptr = sendbuf;
  *sendsize_ptr = strlen(sendbuf) + 1;
  //recvbuf是分配到堆里的,使用完后不要忘记释放掉
  free(recvbuf);
  return;
 
bool stop = false;
 
static void stop_replyserver_handler(int sig) {
  printf("stop_handler\n");
 
  int rv = net_mod_socket_stop(serverSockt);
  if(rv ==0) {
    logger->debug("send stop suc");
    return;
  } else {
    logger->debug("send stop fail.%s\n", bus_strerror(rv));
  }
}
 
void start_recvfrom(int mkey, bool force) {
  logger->debug("start reply\n");
  signal(SIGINT,  stop_replyserver_handler);
  signal(SIGTERM,  stop_replyserver_handler);
 
  serverSockt = net_mod_socket_open();
  if(force) {
    net_mod_socket_force_bind(serverSockt, mkey);
  } else {
    net_mod_socket_bind(serverSockt, mkey);
  }
  
 
  int rv = 0 ;
  while(  true) {
    rv = net_mod_socket_recvandsend(serverSockt, _recvandsend_callback_ , NULL );
    if (rv == 0)
      continue;
    if(rv == EBUS_STOPED) {
      logger->debug("Stopping\n");
      break;
    } else if(rv == EBUS_KEY_INUSED){
      printf("key已经被占用\n");
      exit(1);
    }
    logger->debug("net_mod_socket_recvandsend error.%s\n", bus_strerror(rv));
 
  }
  
  // rv = net_mod_socket_recvandsend_timeout(serverSockt, _recvandsend_callback_ , 0, 2000000, NULL );
  net_mod_socket_close(serverSockt);
  logger->debug("stopted\n");
 
  // while ( (rv = net_mod_socket_recvfrom(ser, &recvbuf, &size, &key) ) == 0) {
  //  // printf( "server: RECEIVED REQUEST FROM  %d NAME %s\n", key, recvbuf);
  //   sprintf(sendbuf, "%d RECEIVED %s", net_mod_socket_get_key(ser), (char *)recvbuf);
  //   net_mod_socket_sendto(ser, sendbuf, strlen(sendbuf) + 1, key);
  //   free(recvbuf);
  // }
}
 
// 交互式客户端
void start_net_client(char *sendlist, char*publist ){
    client = net_mod_socket_open();
    char content[MAXLINE];
    char action[512];
  char topic[512];
  int buskey;
    
    int recv_arr_size, i, n;
    net_mod_recv_msg_t *recv_arr;
  net_mod_err_t *errarr;
  int errarr_size = 0;
 
  pthread_t tid;
  // 创建一个线程接受订阅消息
  pthread_create(&tid, NULL, print_sub_msg, client);
     
  //192.168.5.10:5000:11, 192.168.5.22:5000:11, 192.168.5.104:5000:11
  net_node_t *node_arr;
  int node_arr_size = parse_node_list(sendlist, &node_arr);
    print_node_list(node_arr, node_arr_size);
 
  //192.168.5.10:5000:8, 192.168.5.22:5000:8, 192.168.5.104:5000:8
  net_node_t *pub_node_arr;
    int pub_node_arr_size = parse_node_list(publist, &pub_node_arr);
  print_node_list(pub_node_arr, pub_node_arr_size);
    
  while (true) {
    //printf("Usage: pub <topic> [content] or sub <topic>\n");
    printf("Can I help you? pub,sub,desub,send or quit\n");
    scanf("%s",action);
    
    if(strcmp(action, "pub") == 0) {
        printf("Please input topic and content\n");
      scanf("%s %s", topic, content);
 
        n = net_mod_socket_pub(client, pub_node_arr, pub_node_arr_size, topic, strlen(topic)+1, content, strlen(content)+1);
        printf("pub %d nodes\n", n);
    }
    else if(strcmp(action, "send") == 0) {
        getc(stdin);
        printf("Please input  content\n");
        
          if (fgets(content, MAXLINE, stdin) != NULL) {
              // 收到消息的节点即使没有对应的信息, 也要回复一个表示无的消息,否则会一直等待
            // n = net_mod_socket_sendandrecv(client, node_arr, node_arr_size, content, strlen(content), &recv_arr, &recv_arr_size);
        n = net_mod_socket_sendandrecv_timeout(client, node_arr, node_arr_size, content, strlen(content),
         &recv_arr, &recv_arr_size, &errarr, &errarr_size, 1000);
            printf(" %d nodes reply\n", n);
 
        if(recv_arr_size > 0) {
          for(i=0; i<recv_arr_size; i++) {
            printf("reply from (host:%s, port: %d, key:%d) >> %s\n", 
              recv_arr[i].host,
              recv_arr[i].port,
              recv_arr[i].key,
              (char *)recv_arr[i].content
            );
          }
 
          // 使用完后,不要忘记释放掉
          net_mod_socket_free_recv_msg_arr(recv_arr, recv_arr_size);
        }
            
 
        if(errarr_size > 0) {
          for(i = 0; i < errarr_size; i++) {
            printf("error: (host:%s, port: %d, key:%d) : %s\n", errarr[i].host, errarr[i].port, errarr[i].key, bus_strerror(errarr[i].code));
          }
          free(errarr);
        }
          }
    }
    else if(strcmp(action, "desub") == 0) {
      printf("Please input topic!\n");
       
      scanf("%s", topic);
      if (net_mod_socket_desub(client, topic, strlen(topic)) == 0) {
         printf("%d Desub success!\n", net_mod_socket_get_key(client));
      } else {
        printf("Desub failture!\n");
        exit(0);
      }
     
    } 
    else if(strcmp(action, "sub") == 0) {
      printf("Please input topic!\n");
      scanf("%s",topic);
 
      if (net_mod_socket_sub(client, topic, strlen(topic)) == 0) {
         printf("%d Sub success!\n", net_mod_socket_get_key(client));
      } else {
        printf("Sub failture!\n");
        exit(0);
      }
     
    } 
    else if(strcmp(action, "quit") == 0) {
      break;
    } else {
      printf("error input argument\n");
      continue;
    }
   
  }
  net_mod_socket_close(client);
 
  
}
 
void *_run_one_sendto_many_(void *arg) {
  Targ *targ = (Targ *)arg;
  char sendbuf[128];
 
  int i, j, n;
  int recv_arr_size = 0;
  net_mod_recv_msg_t *recv_arr;
  int total = 0;
  net_mod_err_t *errarr;
  int errarr_size = 0;
 
  int rkey, lkey;
  unsigned int l = 0 , rl;
  const char *hello_format = "%d say Hello %d";
  const char *reply_format = "%d RECEIVED %d say Hello %d";
 
    char filename[128];
    sprintf(filename, "test%d.tmp", targ->node->key);
    FILE *fp = NULL;
    fp = fopen(filename, "w+");
    // fp = stdout;
 
    int recvsize;
    void *recvbuf;
  for (l = 0; l < SCALE; l++) {
    sprintf(sendbuf, hello_format, net_mod_socket_get_key(client), l);
    // fprintf(fp, "requst:%s\n", sendbuf);
    // n = net_mod_socket_sendandrecv(client, node_arr, node_arr_size, sendbuf, strlen(sendbuf) + 1, &recv_arr, &recv_arr_size);
    n = net_mod_socket_sendandrecv_timeout(client, targ->node, 1, sendbuf, strlen(sendbuf) + 1, 
      &recv_arr, &recv_arr_size, &errarr, &errarr_size, 1);
    printf("%d: send %d nodes\n", l, n);
 
    if(recv_arr_size > 0) {
      for(j=0; j < recv_arr_size; j++) {
        fprintf(stdout, "%d send '%s' to %d. received  from (host=%s, port= %d, key=%d) '%s'\n",
          net_mod_socket_get_key(client),
          sendbuf,
          targ->node->key,
          recv_arr[j].host,
          recv_arr[j].port,
          recv_arr[j].key,
          (char *)recv_arr[j].content
        );
 
        printf("key == %d\n", net_mod_socket_get_key(client));
        assert(sscanf((const char *)recv_arr[j].content, reply_format, &rkey, &lkey, &rl) == 3);
        assert(targ->node->key == rkey);
        assert(net_mod_socket_get_key(client) == lkey);
        assert(rl == l);
      }
      // 使用完后,不要忘记释放掉
      net_mod_socket_free_recv_msg_arr(recv_arr, recv_arr_size);
    }
 
    if(errarr_size > 0) {
      for(i = 0; i < errarr_size; i++) {
        printf("error: (host:%s, port: %d, key:%d) : %s\n", errarr[i].host, errarr[i].port, errarr[i].key, bus_strerror(errarr[i].code));
      }
      free(errarr);
    }
    
    total += n;
  }
 
  if(fp != NULL)
    fclose(fp);
  // net_mod_socket_close(client);
  return (void *)total;
}
 
//多线程send
void one_sendto_many(char *nodelist) {
 
  int status, i = 0;
  
  // Targ *targs = (Targ *)calloc(processors, sizeof(Targ));
 
  char sendbuf[512];
  struct timeval start, end;
  long total = 0;
  
  client = net_mod_socket_open();
  net_mod_socket_bind(client, shm_mm_wrapper_alloc_key());
 
  net_node_t *node_arr;
  int node_arr_size = parse_node_list(nodelist, &node_arr);
  Targ targs[node_arr_size];
  pthread_t tids[node_arr_size];
  void *res[node_arr_size];
 
  printf("开始测试...\n");  
  gettimeofday(&start, NULL);
  for (i = 0; i < node_arr_size; i++) {
    targs[i].node = node_arr + i;
    targs[i].id = i;
    pthread_create(&tids[i], NULL, _run_one_sendto_many_, (void *)&targs[i]);
  }
 
  for (i = 0; i < node_arr_size; i++) {
    if (pthread_join(tids[i], &res[i]) != 0) {
      perror("multyThreadClient pthread_join");
    } else {
        total += (long)res[i];
      //fprintf(stderr, "client(%d) 写入 %ld 条数据\n", i, (long)res[i]);
    }
  }
 
  gettimeofday(&end, NULL);
 
  double difftime = end.tv_sec * 1000000 + end.tv_usec - (start.tv_sec * 1000000 + start.tv_usec);
  long diffsec = (long) (difftime/1000000);
  long diffusec = difftime - diffsec*1000000;
  fprintf(stderr,"发送数目:%d, 成功数目: %ld, 用时: (%ld sec %ld usec), 平均: %f\n", 
    SCALE*node_arr_size, total, diffsec, diffusec, difftime/total );
  // fflush(stdout);
 
}
 
// 无限循环send
void test_net_sendandrecv(char *nodelist) {
 
  int i, n, j;
  void * client;
  int recv_arr_size;
  net_mod_recv_msg_t *recv_arr;
  net_node_t *node_arr;
  net_mod_err_t *errarr;
  int errarr_size = 0;
 
  int node_arr_size = parse_node_list(nodelist, &node_arr);
  char buf[128];
  pid_t pid, retPid ;
  unsigned int l , retl;
  int remoteKey;
  const char *hello_format = "%d say Hello %u ";
  const char *reply_format = "%d RECEIVED %d say Hello %d";
 
  pid = getpid();
  l = 0;
 
  client = net_mod_socket_open();
  while(true) {
    sprintf(buf, hello_format, pid, l);
    n = net_mod_socket_sendandrecv_timeout(client, node_arr, node_arr_size, buf, strlen(buf)+1,
      &recv_arr, &recv_arr_size, &errarr, &errarr_size, 1000);
    printf(" %d nodes reply\n", n);
 
    if(recv_arr_size > 0) {
      for(j = 0; j < recv_arr_size; j++) {
        printf("%ld send '%s' . received '%s' from (host:%s, port: %d, key:%d) \n",
          (long)pid,
          buf,
          (char *)recv_arr[j].content,
          recv_arr[j].host,
          recv_arr[j].port,
          recv_arr[j].key
        );
        assert(sscanf((const char *)recv_arr[j].content, reply_format, &remoteKey, &retPid, &retl) == 3);
        assert(retPid == pid);
        assert(retl == l);
        assert(remoteKey == recv_arr[j].key);
      }
      // 使用完后,不要忘记释放掉
      net_mod_socket_free_recv_msg_arr(recv_arr, recv_arr_size);
    }
 
    if(errarr_size > 0) {
      for(i = 0; i < errarr_size; i++) {
        printf("error: (host:%s, port: %d, key:%d) : %s\n", errarr[i].host, errarr[i].port, errarr[i].key, bus_strerror(errarr[i].code));
      }
      free(errarr);
    }
    
    l++;
  }
 
  net_mod_socket_close(client);
 
}
 
void *_run_pub_(void *arg) {
  Targ *targ = (Targ *)arg;
  char sendbuf[128];
 
  int i,j, n;
  int total = 0;
 
  net_node_t *node_arr;
  int node_arr_size = parse_node_list(targ->nodelist, &node_arr);
 
  const char *topic = "news";
  // char filename[512];
  // sprintf(filename, "test%d.tmp", targ->id);
  // FILE *fp = NULL;
  // fp = fopen(filename, "w+");
  // fp = stdout;
 
 
  for (i = 0; i < SCALE; i++) {
    sprintf(sendbuf, "thread(%ld) %d", targ->id, i);
   
    n = net_mod_socket_pub(client, node_arr, node_arr_size, topic, strlen(topic)+1, sendbuf, strlen(sendbuf)+1);
    // n = net_mod_socket_pub(client, node_arr, node_arr_size, sendbuf, strlen(sendbuf) + 1, &recv_arr, &recv_arr_size);
    LoggerFactory::getLogger()->debug( "pub:%s to  %d nodes\n", sendbuf, n);
    total += n;
  }
  // fclose(fp);
 
  return (void *)total;
}
 
//多线程pub
void test_net_pub_threads(char *nodelist) {
 
  int status, i = 0, processors = 4;
  void *res[processors];
  // Targ *targs = (Targ *)calloc(processors, sizeof(Targ));
  Targ targs[processors];
  pthread_t tids[processors];
  char sendbuf[512];
  struct timeval start, end;
  long total = 0;
  client = net_mod_socket_open();
  
printf("开始测试...\n");  
  gettimeofday(&start, NULL);
  for (i = 0; i < processors; i++) {
    targs[i].nodelist = nodelist;
    targs[i].id = i;
    pthread_create(&tids[i], NULL, _run_pub_, (void *)&targs[i]);
  }
 
  for (i = 0; i < processors; i++) {
    if (pthread_join(tids[i], &res[i]) != 0) {
      perror("multyThreadClient pthread_join");
    } else {
      total += (long)res[i];
      //fprintf(stderr, "client(%d) 写入 %ld 条数据\n", i, (long)res[i]);
    }
  }
 
  gettimeofday(&end, NULL);
 
  double difftime = end.tv_sec * 1000000 + end.tv_usec - (start.tv_sec * 1000000 + start.tv_usec);
  long diffsec = (long) (difftime/1000000);
  long diffusec = difftime - diffsec*1000000;
  fprintf(stderr,"发送数目: %ld, 用时: (%ld sec %ld usec), 平均: %f\n", total, diffsec, diffusec, difftime/total );
  // fflush(stdout);
  net_mod_socket_close(client);
}
 
// 无限循环pub
void test_net_pub(char *nodelist) {
 
  int n;
  char sendbuf[512];
  net_node_t *node_arr;
  int node_arr_size = parse_node_list(nodelist, &node_arr);
 
  const char *topic = "news";
  sprintf(sendbuf, "pid:%ld: Good news!!", (long)getpid());
 
  void * client = net_mod_socket_open();
  while (true) {
    n = net_mod_socket_pub(client, node_arr, node_arr_size, topic, strlen(topic)+1, sendbuf, strlen(sendbuf)+1);
    // n = net_mod_socket_pub(client, node_arr, node_arr_size, sendbuf, strlen(sendbuf) + 1, &recv_arr, &recv_arr_size);
    LoggerFactory::getLogger()->debug( "pub to  %d nodes\n", n);
  }
  net_mod_socket_close(client);
}
 
void list () {
  LockFreeQueue<shm_packet_t> * mqueue;
  hashtable_t *hashtable = mm_get_hashtable();
  printf("%10s \t %-10s \t %10s\n", "KEY", "LENGTH", "STATUS");
  hashtable_foreach(hashtable, [&](int key, void * value){
    if(key >= 100 ) {
      mqueue = (LockFreeQueue<shm_packet_t> *)hashtable_get(hashtable, key);
      if((long)mqueue == 0x1) {
        printf("%10d \t %-10s\n", key, "Not In Used");
      } else {
        printf("%10d \t %-10d\n", key, mqueue->size());
      }
     
    } else {
      printf("%10d\n", key);
    }
   
  });
}
 
void info(int key) {
  LockFreeQueue<shm_packet_t> * mqueue;
  hashtable_t *hashtable = mm_get_hashtable();
  mqueue = (LockFreeQueue<shm_packet_t> *) hashtable_get(hashtable, key);
  printf("%10s: %-10p\n", "PTR", mqueue);
  printf("%10s: %-10d\n", "KEY", key);
  printf("%10s: %-10d\n", "LENGTH", mqueue->size());
 
 
}
 
 
void remove(int key) {
  hashtable_t *hashtable = mm_get_hashtable();
  
  LockFreeQueue<shm_packet_t> * mqueue = (LockFreeQueue<shm_packet_t> *)hashtable_get(hashtable, key);
  if(mqueue != NULL) {
    delete mqueue;
    hashtable_remove(hashtable, key);
  }
}
 
void do_sendandrecv(char *sendlist, char *sendbuf) {
  int i, n, j;
  int recv_arr_size;
  net_mod_recv_msg_t *recv_arr;
  net_mod_err_t *errarr;
  int errarr_size = 0;
 
 
  net_node_t *node_arr;
  int node_arr_size = parse_node_list(sendlist, &node_arr);
 
  print_node_list(node_arr, node_arr_size);
 
  void * client = net_mod_socket_open();
  n = net_mod_socket_sendandrecv_timeout(client, node_arr, node_arr_size, sendbuf, strlen(sendbuf) + 1, 
    &recv_arr, &recv_arr_size, &errarr, &errarr_size, 5000);
  
  printf(" %d nodes reply\n", recv_arr_size);
  if(recv_arr_size > 0) {
    for(j=0; j < recv_arr_size; j++) {
 
      fprintf(stdout, "===> suc: %d send '%s'. received  from (host=%s, port= %d, key=%d), '%s'\n\n",
        net_mod_socket_get_key(client),
        sendbuf,
        recv_arr[j].host,
        recv_arr[j].port,
        recv_arr[j].key,
        (char *)recv_arr[j].content
      );
    }
    // 使用完后,不要忘记释放掉
    net_mod_socket_free_recv_msg_arr(recv_arr, recv_arr_size);
  }
// printf("errarr_size = %d\n", errarr_size);
  if(errarr_size > 0) {
    for(i = 0; i < errarr_size; i++) {
      printf("===> error: (host:%s, port: %d, key:%d). %s\n", errarr[i].host, errarr[i].port, errarr[i].key, bus_strerror(errarr[i].code));
    }
    free(errarr);
  }
 
  net_mod_socket_close(client);
}
 
 
 
void usage(char *name)
{
  #define fpe(str) fprintf(stderr, "  %s", str);
 
  fprintf(stderr, "Usage: %s {function} [OPTIONS]  [ARG...]\n\n", name);
  fprintf(stderr, "Test shmsocket\n\n");
 
  fprintf(stderr, "Options:\n\n");
  fpe("-p, --port                           TCP/IP Port\n");
  fpe("-k, --key                            SHM Key\n");
  fpe("--sendlist                           format:--sendlist=\"192.168.5.10:5000:11, 192.168.5.22:5000:11, 192.168.20.104:5000:11\"\n");
  fpe("--publist                            format: --publist=\"192.168.5.10:5000:8, 192.168.5.22:5000:8, 192.168.20.104:5000:8\"\n");
  fpe("\n");
 
  fprintf(stderr, "Examples:\n\n");
  fpe("# sendandrecv to socket which has key 100\n");
  fpe("./shm_util sendandrecv 100 \"hello\"\n");
  fpe("# list all key\n");
  fpe("./shm_util list\n");
  fpe("# remove  key 1001\n");
  fpe("./shm_util rm 1001\n");
  fpe("./shm_util info 1002\n");
  fpe("./shm_util recvfrom --bind 1002 [--force]\n")
  fpe("\n");
}
 
 
 
argument_t parse_args (int argc, char *argv[])
{
  int c;
 
  if(argc < 2) {
    usage(argv[0]);
    exit(1);
  }
 
  
  
  argument_t mopt = {};
  
  // mopt.volume_list_size = 0;
  mopt.interactive = false;
 
  opterr = 0;
 
 
  static struct option long_options[] =
  {
    /* These options set a flag. */
     
    {"key",  required_argument, 0, 'k'},
    {"port",  required_argument, 0, 'p'},
    {"interactive",  no_argument, 0, 'i'},
    {"force",  no_argument, 0, 'f'},
    {"bind",  required_argument, (int *)mopt.bind, 0},
    {"sendlist",  required_argument, (int *)mopt.sendlist, 0},
    {"publist",  required_argument, (int *)mopt.publist, 0},
    {0, 0, 0, 0}
  };
  /* getopt_long stores the option index here. */
  int option_index = 0;
  while (1)
  {
    
 
    c = getopt_long (argc, argv, "+fk:p:i", long_options, &option_index);
 
    /* Detect the end of the options. */
    if (c == -1)
      break;
 
    switch (c)
    {
    case 0:
      /* If this option set a flag, do nothing else now. */
      if (long_options[option_index].flag != 0)
        break;
     
      if(strcmp(long_options[option_index].name, "sendlist") == 0) {
        mopt.sendlist = optarg;
      }
      else if(strcmp(long_options[option_index].name, "publist") == 0) {
        mopt.publist = optarg;
      }
      else if(strcmp(long_options[option_index].name, "bind") == 0) {
        mopt.bind = atoi(optarg);
      }
      else {
        printf ("option %s", long_options[option_index].name);
        if (optarg)
          printf (" with arg %s", optarg);
        printf ("\n");
      }
    
      break;
     
    case 'k':
      mopt.key = atoi(optarg);
      break;
 
    case 'i':
      mopt.interactive = true;
      break;
 
    case 'f':
      mopt.force = true;
      break;
 
    case 'p':
       // printf ("==name with value `%s'\n", optarg);
      mopt.port = atoi(optarg);
      break;
 
    case '?':
     printf ("==? optopt=%c, %s, `%s', %d\n", optopt, optarg, argv[optind], optind);
      /* getopt_long already printed an error message. */
      usage(argv[0]);
      exit(1);
      break;
 
    default:
      //printf ("==default optopt=%c, %s, `%s'\n",optopt, optarg,  argv[optind]);
      break;
    }
  }
 
  // printf ("optind = %d, argc=%d \n", optind, argc);
  /* Print any remaining command line arguments (not options). */
  if (optind < argc)
  {
    mopt.cmd_arr = &argv[optind];
    mopt.cmd_arr_len = argc - optind;
    // printf ("non-option ARGV-elements: ");
    // while (optind < argc)
    //   printf ("%d, %d, %s \n", optind, argc, argv[optind++]);
    // putchar ('\n');
  }
  return mopt;
 
}
 
 
/**
 * @str "192.168.5.10:5000:11, 192.168.5.22:5000:11, 192.168.5.104:5000:11"
 * @node_arr_addr 返回处理后的网络节点数组 
 * {
 *   {"192.168.5.22", 5000, 11},
 *   {"192.168.20.10", 5000, 11},
 *   {"192.168.20.104", 5000, 11}
 * }
 * @return 数组的长度
 */
int parse_node_list(const char *str, net_node_t *node_arr_addr[]) {
  int i, j;
  char **property_arr;
  int property_arr_len;
  char **entry_arr;
  int entry_arr_len = str_split(str, ",", &entry_arr);
 
  net_node_t *node_arr = (net_node_t *) calloc(entry_arr_len, sizeof(net_node_t));
  for(i = 0; i < entry_arr_len; i++) {
    if(strchr(entry_arr[i], ':') == NULL) {
      node_arr[i]= {NULL, 0, atoi(entry_arr[i])};
      continue;
    }
    property_arr_len = str_split(entry_arr[i], ":", &property_arr);
   printf("=====%s, %s, %s\n", property_arr[0], property_arr[1], property_arr[2]);
 
    node_arr[i] = {trim(property_arr[0], 0), atoi(property_arr[1]), 0};
   
    free(property_arr[1]);
    if(property_arr_len == 3) {
      node_arr[i].key = atoi(property_arr[2]);
      free(property_arr[2]);
    }
    free(entry_arr[i]);
   
  }
  *node_arr_addr = node_arr;
 
 
  return entry_arr_len;
}
 
void print_node_list(net_node_t *node_arr, int len) {
  printf("============node list begin==========\n");
  for(int i = 0; i < len; i++) {
    printf("host=%s, port=%d, key=%d \n", node_arr[i].host,  node_arr[i].port,  node_arr[i].key);
  }
  printf("============node list end==========\n");
}
 
 
 
 
int main(int argc, char *argv[]) {
  int i;
  char *prog;
  char * fun;
  argument_t opt = {};
 
  shm_mm_wrapper_init(512);
 
  if(argc < 2) {
    usage(argv[0]);
    exit(1);
  }
  prog = argv[0];
  fun = argv[1];
  argc--;
  argv++;
 
 
  if (strcmp("help", fun) == 0 ) {
    usage(prog);
  }
  else if (strcmp("list", fun) == 0 ) {
    list();
  }
  else if (strcmp("info", fun) == 0 ) {
    if(argc < 2) {
 
      usage(prog);
      
    } else {
      for(i = 1; i < argc; i++) {
        int key = atoi(argv[i]);
        info(key);
      }
    }
  }
  else if (strcmp("rm", fun) == 0 ) {
    if(argc < 2) {
      usage(prog);
      
    } else {
       for(i = 1; i < argc; i++) {
        int key = atoi(argv[i]);
        remove(key);
      }
    }
   
  }
  else if (strcmp("sendandrecv", fun) == 0 ) {
    if(argc < 3) {
      usage(prog);
      exit(1);
    }
    char *sendlist = argv[1];
    char *content = argv[2];
    do_sendandrecv(sendlist, content);
  }
  else if (strcmp("start_bus_server", fun) == 0) {
   
    start_bus_server(opt);
  }
  else if (strcmp("start_resycle", fun) == 0) {
    
    start_resycle();
  }
 
  else if (strcmp("start_net_proxy", fun) == 0 ) {
    opt =  parse_args(argc, argv);
    if(opt.port == 0) {
      usage(prog);
      exit(1);
    }
    start_net_proxy(opt);
    
  }
  
  else if (strcmp("recvfrom", fun) == 0) {
    opt =  parse_args(argc, argv);
    if(opt.bind == 0) {
      usage(argv[0]);
    } else {
      start_recvfrom(opt.bind, opt.force);
    }
    
  }
  else if (strcmp("start_net_client", fun) == 0) {
    opt =  parse_args(argc, argv);
    if(opt.sendlist == 0) {
      fprintf(stderr, "Missing sendlist .\n");
      usage(argv[0]);
      exit(1);
    }
    if(opt.publist == 0) {
      fprintf(stderr, "Missing publist.\n");
      usage(argv[0]);
      exit(1);
    }
    start_net_client(opt.sendlist, opt.publist);
  }
  else if (strcmp("one_sendto_many", fun) == 0) {
    opt =  parse_args(argc, argv);
    if(opt.sendlist == 0) {
      fprintf(stderr, "Missing sendlist .\n");
      usage(argv[0]);
      exit(1);
    }
     
    one_sendto_many(opt.sendlist);
  }
  else if (strcmp("test_net_sendandrecv", fun) == 0) {
    opt =  parse_args(argc, argv);
    if(opt.sendlist == 0) {
      fprintf(stderr, "Missing sendlist .\n");
      usage(argv[0]);
      exit(1);
    }
     
    test_net_sendandrecv(opt.sendlist);
  }
  else if (strcmp("test_net_pub_threads", fun) == 0) {
    opt =  parse_args(argc, argv);
    if(opt.publist == 0) {
      fprintf(stderr, "Missing publist .\n");
      usage(argv[0]);
      exit(1);
    }
     
    test_net_pub_threads(opt.publist);
  }
  else if (strcmp("test_net_pub", fun) == 0) {
    opt =  parse_args(argc, argv);
    if(opt.publist == 0) {
      fprintf(stderr, "Missing publist .\n");
      usage(argv[0]);
      exit(1);
    }
     
    test_net_pub(opt.publist);
  }
 
  else {
    printf("Invalid funciton name\n");
    usage(argv[0]);
    exit(1);
 
  }
 
  shm_mm_wrapper_destroy();
 
}