-
Notifications
You must be signed in to change notification settings - Fork 5
/
MPWide.cpp
1598 lines (1350 loc) · 47.4 KB
/
MPWide.cpp
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
/**************************************************************
* This file is part of the MPWide communication library
*
* Written by Derek Groen with thanks going out to Steven Rieder,
* Simon Portegies Zwart, Joris Borgdorff, Hans Blom and Tomoaki Ishiyama.
* for questions, please send an e-mail to:
* djgroennl@gmail.com
* MPWide is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* MPWide is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MPWide. If not, see <http://www.gnu.org/licenses/>.
* **************************************************************/
#include "MPWide.h"
#include "Socket.h"
#include <iostream>
#include <fstream>
#include <string>
#include <errno.h>
#include <sys/time.h>
#include <pthread.h>
#include <cstdlib>
#include <vector>
#include <unistd.h>
#include "serialization.h"
#include "mpwide-macros.h"
// forward declarations
class MPWPath;
struct thread_tmp;
bool MPWideAutoTune = true;
/* STREAM-specific definitions */
static int *port = NULL;
static int *cport = NULL;
static int *isclient = NULL;
static Socket **client = NULL;
static std::string *remote_url = NULL;
/* global thread memory */
static thread_tmp** ta = NULL;
// length of all the above vectors:
static int num_streams = 0;
/* List of paths. */
static MPWPath **paths = NULL;
static int num_paths = 0;
/* Send and Recv occurs in chunks of size tcpbuf_ssize/rsize.
* Setting this to 1MB or higher gave problems with Amsterdam-Drexel test. */
static int tcpbuf_ssize = 8*1024;
static int tcpbuf_rsize = 8*1024;
static int relay_ssize = 8*1024;
static int relay_rsize = 8*1024;
/* PATH-specific definitions */
class MPWPath {
public:
std::string remote_url; // end-point of the path
int *streams; // id numbers of the streams used
int num_streams; // number of streams
MPWPath(std::string remote_url, int* str, int numstr)
: remote_url(remote_url), num_streams(numstr)
{
streams = new int[numstr];
memcpy(streams, str, num_streams*sizeof(int));
}
~MPWPath() { delete [] streams; }
};
/* thread information */
struct thread_tmp {
long long int sendsize, recvsize;
long long int* dyn_recvsize; //For DynEx.
int thread_id;
int channel;
int numchannels;
int numrchannels; //Cycle only.
char* sendbuf;
char* recvbuf;
};
/* socket startup information */
struct init_tmp {
int stream;
Socket *sock;
int port;
int cport;
bool server_wait;
bool connected;
};
/** MPW_PacingMode
* MPWide is able to have PacingMode either enabled or disabled. By default, the PacingMode is enabled, and MPWide will insert very
* short usleep messages between communication calls. These usleep statements often help reduce the chance of overflowing the transfer
* buffers of local network interfaces, which in turn result in worse and less stable performance.
*/
#if MPW_PacingMode == 1
static double pacing_rate = 100*1024*1024; //Pacing rate per stream. This is the maximum throughput in bytes/sec possible for each stream.
static useconds_t pacing_sleeptime = useconds_t(1000000/(pacing_rate/(1.0*tcpbuf_ssize))); //Sleep time for SendRecvs in microseconds.
extern "C" {
double MPW_getPacingRate() {
return pacing_rate;
}
void MPW_setPacingRate(double rate) {
if(rate == -1) {
pacing_rate = -1;
pacing_sleeptime = 0;
}
else {
pacing_rate = rate;
pacing_sleeptime = useconds_t(1000000/(pacing_rate/(1.0*tcpbuf_ssize)));
LOG_INFO("Pacing enabled, rate = " << pacing_rate << " => delay = " << pacing_sleeptime << " us.");
}
}
}
/* autotunePacingRate selects an appropriate pacing rate depending on the number of streams selected. */
static void autotunePacingRate()
{
int max_streams = 0;
for(int i = 0; i < num_paths; i++)
{
if (paths[i] && paths[i]->num_streams > max_streams)
max_streams = paths[i]->num_streams;
}
if (max_streams < 3)
MPW_setPacingRate(1200*1024*1024);
else
MPW_setPacingRate((1200*1024*1024)/max_streams);
}
#endif // MPW_PacingMode == 1
void MPW_setAutoTuning(bool b) {
MPWideAutoTune = b;
}
bool MPW_AutoTuning() {
return MPWideAutoTune;
}
static void showSettings()
{
LOG_INFO("-----------------------------------------------------------");
LOG_INFO("MPWide Settings:");
LOG_INFO("Chunk Size (send/recv): " << tcpbuf_ssize << "/" << tcpbuf_rsize);
LOG_INFO("Relay pace (send/recv): " << relay_ssize << "/" << relay_rsize);
LOG_INFO("Number of streams : " << num_streams);
LOG_INFO("tcp buffer parameter : " << WINSIZE);
LOG_INFO("pacing rate : " << pacing_rate << " bytes/s.");
#ifdef MONITORING
LOG_INFO("bandwidth monitoring : " << MONITORING);
#else
LOG_INFO("bandwidth monitoring : 0")
#endif
LOG_INFO("-----------------------------------------------------------");
LOG_INFO("END OF SETUP PHASE.");
}
#ifdef PERF_TIMING
double GetTime(){
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + 1.0e-6*tv.tv_usec;
}
double BarrierTime = 0.0; //4 newly introduced globals for monitoring purposes
double SendRecvTime = 0.0;
double PackingTime = 0.0;
double UnpackingTime = 0.0;
#endif
void MPW_setChunkSize(int sending, int receiving) {
tcpbuf_ssize = sending;
tcpbuf_rsize = receiving;
LOG_DEBUG("Chunk Size modified to: " << sending << "/" << receiving << ".");
}
/* MPW_DNSResolve converts a host name to an ip address. */
char *MPW_DNSResolve(char *host){
if(isdigit(host[0])) {
return host;
}
const hostent* host_info = 0 ;
for( int i=0; (host_info==0) && (i<4); i++) {
host_info = gethostbyname(host);
}
if(host_info) {
const in_addr* address = (in_addr*)host_info->h_addr_list[0] ;
host = (char*) (inet_ntoa(*address));
LOG_DEBUG(" address found: " << host);
return host;
}
LOG_ERR("Error: Unable to resolve host name");
return NULL;
}
char *MPW_DNSResolve(std::string host) {
return MPW_DNSResolve((char *)host.c_str());
}
inline int selectSockets(int wchannel, int rchannel, int mask)
/* Returns:
0 if no access.
1 if read on read channel.
2 if write on write channel.
3 if both. */
{
return Socket_select(client[rchannel]->getSock(), client[wchannel]->getSock(), mask, 10, 0);
}
int MPW_NumChannels(){
return num_streams;
}
#if MONITORING == 1
long long int bytes_sent;
bool stop_monitor = false;
#ifdef PERF_TIMING
/* Performs per-second throughput monitoring in real-time */
void *MPW_TBandwidth_Monitor(void *args)
{
std::ofstream myfile;
myfile.open("bandwidth_monitor.txt");
long long int old_bytes_sent = 0;
long long int cur_bytes_sent = 0;
long long int old_time = 0;
while(!stop_monitor) {
if(old_time != int(GetTime())) {
cur_bytes_sent = bytes_sent;
myfile << "time: " << int(GetTime()) << " bandwidth: " << cur_bytes_sent - old_bytes_sent << std::endl;
old_bytes_sent = cur_bytes_sent;
old_time = int(GetTime());
}
usleep(1000);
}
myfile.close();
return NULL;
}
#endif // ifdef PERF_TIMING
#endif // MONITORING == 1
/* Initialize a single MPWide TCP stream (used within a pthread). */
void* MPW_InitStream(void* args)
{
init_tmp &t = *((init_tmp *) args);
Socket *sock = t.sock;
const int stream = t.stream;
const int port = t.port;
const int cport = t.cport;
const bool server_wait = t.server_wait;
if(isclient[stream]) {
sock->create();
/* Patch to bypass firewall problems. */
if(cport>0) {
LOG_DEBUG("[" << stream << "] Trying to bind as client at " << (cport));
int bound = sock->bind(cport);
}
/* End of patch*/
t.connected = sock->connect(remote_url[stream],port);
LOG_WARN("Server wait & connected " << server_wait << "," << t.connected);
#if InitStreamTimeOut == 0
if (!server_wait) {
while(!t.connected) {
usleep(50000);
t.connected = client[stream].connect(remote_url[stream],port);
}
}
#endif
LOG_DEBUG("[" << stream << "] Attempt to connect as client to " << remote_url[stream]
<<" at port " << port << ": " << t.connected);
}
if(!t.connected) {
sock->close();
if (server_wait) {
sock->create();
bool bound = sock->bind(port);
LOG_DEBUG("[" << stream << "] Trying to bind as server at " << port << ". Result = " << bound);
if (!bound) {
LOG_WARN("Bind on ch #"<< stream <<" failed.");
sock->close();
return NULL;
}
if (sock->listen()) {
t.connected = sock->accept();
LOG_DEBUG("[" << stream << "] Attempt to act as server: " << t.connected);
if (t.connected) { isclient[stream] = 0; }
}
else {
LOG_WARN("Listen on ch #"<< stream <<" failed.");
sock->close();
return NULL;
}
}
}
return NULL;
}
/* Close down individual streams. */
void MPW_CloseChannels(int* channel, int numchannels)
{
for(int i = 0; i < numchannels; i++) {
LOG_INFO("Closing channel #" << channel[i] << " with port = " << port[i] << " and cport = " << cport[i]);
client[channel[i]]->close();
}
}
/* Add new MPWide streams that are associated to a single MPWide Path. */
void MPW_AddStreams(std::string* url, int* ports, int* cports, const int *stream_indices, const int numstreams) {
if (client == NULL) {
client = new Socket*[MAX_NUM_STREAMS];
port = new int[MAX_NUM_STREAMS];
cport = new int[MAX_NUM_STREAMS];
isclient = new int[MAX_NUM_STREAMS];
remote_url = new std::string[MAX_NUM_STREAMS];
ta = new thread_tmp*[MAX_NUM_STREAMS];
paths = new MPWPath*[MAX_NUM_PATHS];
#ifdef PERF_TIMING
#if MONITORING == 1
pthread_t monitor;
int code = pthread_create(&monitor, NULL, MPW_TBandwidth_Monitor, NULL);
#endif
#endif
}
for(int i = 0; i < numstreams; i++) {
const int stream = stream_indices[i];
client[stream] = new Socket();
port[stream] = ports[i];
ta[stream] = new thread_tmp;
ta[stream]->channel = stream;
LOG_INFO("Stream number " << stream);
remote_url[stream] = MPW_DNSResolve(url[i]);
LOG_DEBUG("MPW_DNSResolve resolves " << url[i] << " to address " << remote_url[stream] << ".");
if(url[i].compare("0") == 0 || url[i].compare("0.0.0.0") == 0) {
isclient[stream] = 0;
cport[stream] = -1;
LOG_INFO("Empty IP address given: Switching to Server-only mode.");
} else {
isclient[stream] = 1;
cport[stream] = cports[i];
}
LOG_DEBUG(url[i] << " " << ports[i] << " " << cports[i]);
}
}
int MPW_InitStreams(int *stream_indices, int numstreams, bool server_wait) {
pthread_t streams[numstreams];
init_tmp t[numstreams];
for(int i = 0; i < numstreams; i++) {
int stream = stream_indices[i];
t[i].stream = stream;
t[i].sock = client[stream];
t[i].port = port[stream];
t[i].cport = cport[stream];
t[i].server_wait = server_wait;
t[i].connected = false;
if(i>0) {
int code = pthread_create(&streams[i], NULL, MPW_InitStream, &t[i]);
}
}
if(numstreams > 0) {
MPW_InitStream(&t[0]);
}
for(int i = 1; i < numstreams; i++) {
pthread_join(streams[i], NULL);
}
/* Error handling code (in case MPW_InitStream times out for one or more */
// closing itself is done by caller
bool all_connected = true;
for(int i = 0; i < numstreams; i++) {
if(t[i].connected == false) {
LOG_WARN("One connection has failed: #" << stream_indices[i]);
all_connected = false;
}
}
if (all_connected)
return 0;
else
return -1;
}
static int reserveAvailableStreamNumber(int total_streams)
{
int streak = 0;
/* Get next available contiguous streams */
for (int i = 0; i < num_streams; i++) {
if (client[i] == NULL) {
if (++streak == total_streams)
// Don't modify num_streams
return i + 1 - total_streams;
} else if (streak) {
streak = 0;
}
}
// fall through
if (num_streams + total_streams <= MAX_NUM_STREAMS) {
const int stream_number = num_streams;
num_streams += total_streams;
return stream_number;
} else {
LOG_ERR("ERROR: trying to create more than " << MAX_NUM_STREAMS << " streams");
return -1;
}
}
static int reserveAvailablePathNumber()
{
/* Get next available path */
for (int i = 0; i < num_paths; ++i) {
if (paths[i] == NULL)
return i;
}
// fall through
if (num_paths < MAX_NUM_PATHS) {
return num_paths++;
} else {
LOG_ERR("ERROR: trying to create more than " << MAX_NUM_PATHS << " paths");
return -1;
}
}
/* Initialize the MPWide. set client to 1 for one machine, and to 0 for the other. */
int MPW_Init(std::string* url, int* ports, int* cports, int numstreams)
{
LOG_INFO("Initialising...");
const int start_stream = reserveAvailableStreamNumber(numstreams);
if (start_stream == -1) return -1;
int stream_indices[numstreams];
for(int i = 0; i < numstreams; i++) {
stream_indices[i] = start_stream + i; //if this is the first MPW_Init, then num_streams still equals 0 here.
}
MPW_AddStreams(url, ports, cports, stream_indices, numstreams);
int ret = MPW_InitStreams(stream_indices, numstreams, true);
showSettings();
return ret;
}
/* Constructs a path. Return path id or negative error value. */
int MPW_CreatePathWithoutConnect(std::string host, int server_side_base_port, const int streams_in_path) {
const int start_stream = reserveAvailableStreamNumber(streams_in_path);
const int path_id = reserveAvailablePathNumber();
if (start_stream == -1 || path_id == -1) return -1;
int path_ports[streams_in_path];
int path_cports[streams_in_path];
std::string *hosts = new std::string[streams_in_path];
int stream_indices[streams_in_path];
for(int i = 0; i < streams_in_path; i++) {
path_ports[i] = server_side_base_port + i;
path_cports[i] = -2;
hosts[i] = host;
stream_indices[i] = start_stream + i;
}
MPW_AddStreams(hosts, path_ports, path_cports, stream_indices, streams_in_path);
delete [] hosts;
paths[path_id] = new MPWPath(host, stream_indices, streams_in_path);
#if MPW_PacingMode == 1
if(MPWideAutoTune) {
autotunePacingRate();
}
#endif
LOG_INFO("Creating New Path:");
LOG_INFO(host << " " << server_side_base_port << " " << streams_in_path << " streams.");
for(int i=0; i<streams_in_path; i++) {
LOG_DEBUG("Stream[" << i << "]: " << paths[path_id]->streams[i]);
}
/* Return the identifier for the MPWPath we just created. */
return path_id;
}
/** Connect a path that has been created and provided with streams, to a remote endpoint,
* or have it act as a server.
*/
int MPW_ConnectPath(int path_id, bool server_wait) {
int ret = MPW_InitStreams(paths[path_id]->streams, paths[path_id]->num_streams, server_wait);
if (MPWideAutoTune && ret >= 0)
{
const int default_window = 32*1024*1024/paths[path_id]->num_streams;
for(int j = 0; j < paths[path_id]->num_streams; j++)
MPW_setWin(paths[path_id]->streams[j], default_window);
}
showSettings();
return ret;
}
/* Creates and connects a path */
int MPW_CreatePath(std::string host, int server_side_base_port, int streams_in_path) {
int path_id = MPW_CreatePathWithoutConnect(host, server_side_base_port, streams_in_path);
int status = MPW_ConnectPath(path_id, true);
if(status < 0) {
MPW_DestroyPath(path_id);
return -1;
}
return path_id;
}
extern "C" {
int MPW_CreatePath_c (char* host, int server_side_base_port, int streams_in_path) {
return MPW_CreatePath(host, server_side_base_port, streams_in_path);
}
}
/* Remove a stream from a path. */
void EraseStream(int stream) {
delete client[stream];
client[stream] = NULL;
delete ta[stream];
// Deleted last stream, move the stream counter back
if (stream + 1 == num_streams) {
for (int i = stream - 1; i >= 0; --i) {
if (client[i] != NULL) {
num_streams = i + 1;
return;
}
}
// If no streams are found, num_streams is 0
num_streams = 0;
}
}
/* Attempt to change the TCP window size for a single stream. */
void MPW_setWin(int stream, int size) {
client[stream]->setWin(size);
}
/* Attempt to change the TCP window size for a single path. */
void MPW_setPathWin(int path, int size) {
for(int i=0; i < paths[path]->num_streams; i++) {
client[paths[path]->streams[i]]->setWin(size);
}
}
/** Destroy an MPWide path (disconnect, then delete).
* Return 0 on success (negative on failure).
*/
int MPW_DestroyPath(int path) {
for (int j = 0; j < paths[path]->num_streams; j++) {
EraseStream(paths[path]->streams[j]);
}
delete paths[path];
paths[path] = NULL;
// Reset num_paths, if this was the last path
if (path == num_paths - 1) {
for (int i = path - 1; i >= 0; --i) {
if (paths[i] != NULL) {
num_paths = i + 1;
return 0;
}
}
// If no paths are found, num_streams is 0
num_paths = 0;
}
return 0;
}
extern "C" {
/* Path-based Send and Recv operations*/
int MPW_DSendRecv(char* sendbuf, long long int sendsize, char* recvbuf, long long int maxrecvsize, int path) {
return MPW_DSendRecv(sendbuf, sendsize, recvbuf, maxrecvsize, paths[path]->streams, paths[path]->num_streams);
}
int MPW_SendRecv(char* sendbuf, long long int sendsize, char* recvbuf, long long int recvsize, int path) {
return MPW_SendRecv(sendbuf, sendsize, recvbuf, recvsize, paths[path]->streams, paths[path]->num_streams);
}
int MPW_Send(char* sendbuf, long long int sendsize, int path) {
return MPW_SendRecv(sendbuf, sendsize, NULL, 0, paths[path]->streams, paths[path]->num_streams);
}
int MPW_Recv(char* recvbuf, long long int recvsize, int path) {
return MPW_SendRecv(NULL, 0, recvbuf, recvsize, paths[path]->streams, paths[path]->num_streams);
}
}
/* Legacy initialization function for MPWide that does not require client port binding. */
int MPW_Init(std::string* url, int* ports, int numstreams)
{
int cports[numstreams];
for(int i=0; i<numstreams; i++) {
cports[i] = -1;
}
return MPW_Init(url, ports, cports, numstreams);
}
/* Legacy shorthand initialization call for local processes that use a single stream. */
int MPW_Init(std::string url, int port) {
std::string u1[1] = {url};
int p1[1] = {port};
return MPW_Init(u1,p1,1);
}
/* AS the last two functions, but then compatible for C. */
extern "C" {
int MPW_Init_c (char** url, int* ports, int numstreams)
{
std::string* urls = new std::string[numstreams];
for(int i=0;i<numstreams;i++) {
urls[i].assign(url[i]);
}
int status = MPW_Init(urls,ports,numstreams);
delete [] urls;
return status;
}
int MPW_Init1_c (char* url, int port)
{
return MPW_Init(url, port);
}
}
/* Close all sockets and free data structures related to the library. */
int MPW_Finalize()
{
#if MONITORING == 1
stop_monitor = true;
#endif
for (int i = 0; i < num_paths; i++) {
if (paths[i])
delete paths[i];
}
delete [] paths;
num_paths = 0;
for (int i = 0; i < num_streams; i++) {
if (client[i]) {
delete client[i];
delete ta[i];
}
}
delete [] client;
delete [] ta;
delete [] port;
delete [] cport;
delete [] remote_url;
delete [] isclient;
num_streams = 0;
LOG_INFO("MPWide sockets are closed.");
// Wait on any closing sockets
sleep(1);
return 1;
}
/* Wrapping function for SendRecv in case no receiving is required. */
void MPW_Send(char* sendbuf, long long int size, int* channels, int num_channels)
{
MPW_SendRecv(sendbuf,size,NULL,0,channels,num_channels);
}
/* Wrapping function for SendRecv in case no sending is required. */
void MPW_Recv(char* buf, long long int size, int* channels, int num_channels)
{
MPW_SendRecv(NULL,0,buf,size,channels,num_channels);
}
/* Send/Recv (part of) the data between two processes using a single TCP stream and a single thread. */
int *InThreadSendRecv(char* const sendbuf, const long long int sendsize, char* const recvbuf, const long long int recvsize, const int base_channel)
{
int * const ret = new int(0);
#ifdef PERF_TIMING
double t = GetTime();
#endif
long long int a = 0;
long long int b = 0;
const Socket *wsock = client[base_channel % 65536];
const Socket *rsock = base_channel < 65536 ? wsock : client[(base_channel/65536) - 1];
int mask = (recvsize == 0 ? MPWIDE_SOCKET_RDMASK : 0)
| (sendsize == 0 ? MPWIDE_SOCKET_WRMASK : 0);
while (mask != (MPWIDE_SOCKET_RDMASK|MPWIDE_SOCKET_WRMASK)) {
const int mode = Socket_select(rsock->getSock(), wsock->getSock(), mask, 10, 0);
if (mode == -1) {
// Continue after interrupt, but fail on other messages
if (errno == EINTR)
continue;
else {
*ret = -max(1, errno);
break;
}
}
if(FLAG_CHECK(mode,MPWIDE_SOCKET_RDMASK)) {
const int n = rsock->irecv(recvbuf + b, min(tcpbuf_rsize,recvsize - b));
if (n <= 0) {
if (n == 0) // socket disconnected on other side, choose default -1 errno.
*ret = -1;
else
*ret = -max(1, errno);
break;
}
b += n;
#if MONITORING == 1
bytes_sent += n;
#endif
if(b == recvsize)
mask |= MPWIDE_SOCKET_RDMASK; //don't check for read anymore
}
if(FLAG_CHECK(mode,MPWIDE_SOCKET_WRMASK)) {
const int n = wsock->isend(sendbuf + a, min(tcpbuf_ssize, sendsize - a));
if (n < 0) {
*ret = -errno;
break;
}
a += n;
#if MONITORING == 1
bytes_sent += n;
#endif
if(a == sendsize)
mask |= MPWIDE_SOCKET_WRMASK; //don't check for write anymore
}
#if MPW_PacingMode == 1
usleep(pacing_sleeptime);
#endif
}
#ifdef PERF_TIMING
t = GetTime() - t;
LOG_DEBUG("This Send/Recv took: " << t << "s. Rate: " << (sendsize+recvsize)/(t*1024*1024)
<< "MB/s. ch=" << (base_channel % 65536) << "/" << ((base_channel/65536) - 1));
SendRecvTime += t;
#endif
return ret;
}
/* Data type intended to contain information for MPW_Relay (which relies on threads) */
typedef struct relay_struct{
int channel;
int channel2;
int bufsize;
}relay_struct;
/* MPWide Relay function: Provides two-way relay over one channel. */
void* MPW_Relay(void* args)
{
relay_struct *r = (relay_struct *)args;
int mode = 0;
int mode2 = 0;
long long int n = 0;
long long int ns = 0;
long long int n2 = 0;
long long int ns2 = 0;
int channel = r->channel;
int channel2 = r->channel2;
int bufsize = r->bufsize;
char* buf = (char *) malloc(bufsize);
char* buf2 = (char *) malloc(bufsize);
LOG_DEBUG("Starting Relay Channel #" << channel);
int tmp = 0;
while(1) {
mode = client[channel]->select_me(0);
mode2 = client[channel2]->select_me(0);
//std::cout << "mode/mode2 = " << mode << "/" << mode2 << "--" << n << "/" << n2 << "/" << ns << "/" << ns2 <<std::endl;
/* Recv from channel 1 */
if(mode%2 == 1) {
if(n == ns) {
n = 0; ns = 0;
}
tmp = client[channel]->irecv(buf+n,min(bufsize-n,relay_rsize));
n += tmp;
LOG_TRACE("Retrieved from 1: " << n);
}
/* ...forward to channel 2. */
if(mode2/2 == 1 && n > 0) {
tmp = client[channel2]->isend(buf+ns,min(n-ns,relay_ssize));
ns += tmp;
LOG_TRACE("Sent to 2: " << ns);
}
// Recv from channel 2
if(mode2%2 == 1) {
if(n2 == ns2) {
n2 = 0; ns2 = 0;
}
tmp = client[channel2]->irecv(buf2+n2,min(bufsize-n2,relay_rsize));
n2 += tmp;
LOG_TRACE("Retrieved from 2: " << n2);
}
// ...forward to channel 1.
if(mode/2 == 1 && n2 > 0) {
tmp = client[channel]->isend(buf2+ns2,min(n2-ns2,relay_ssize));
ns2 += tmp;
LOG_TRACE("Sent to 1: " << ns2);
}
#if MPW_PacingMode == 1
usleep(pacing_sleeptime);
#endif
}
free(buf);
free(buf2);
return NULL;
}
/* Unused function that can allow automatic termination when a file named 'stop' is present. */
void* CheckStop(void* args) {
while(true) {
if(!access("stop",F_OK)) {
MPW_Finalize();
remove("stop");
exit(0);
}
sleep(2);
}
}
/* MPW_Relay:
* redirects [num_channels] streams in [channels] to the respective
* streams in [channels2] and vice versa. */
void MPW_Relay(int* channels, int* channels2, int num_channels) {
int bufsize = max(relay_ssize,relay_rsize);
pthread_t streams[num_channels*2];
relay_struct rstruct[num_channels*2];
for(int i = 0; i < num_channels; i++) {
rstruct[i].channel = channels[i];
rstruct[i].channel2 = channels2[i];
rstruct[i].bufsize = bufsize;
int code = pthread_create(&streams[i], NULL, MPW_Relay, &rstruct[i]);
}
for(int i = 0; i < num_channels*2; i++) {
pthread_join(streams[i], NULL);
}
return;
}
/* Dynamically sized Send/Recv between two processes. */
void *MPW_TDynEx(void *args)
{
bool cycling = false;
thread_tmp *ta = (thread_tmp *)args;
if (ta->channel > 65535) { cycling = true; }
char * sendbuf = ta->sendbuf;
long long int totalsendsize = ta->sendsize;
long long int recvsize = ta->recvsize;
// Maximum size permitted for message.
long long int maxrecvsize = recvsize;
char* recvbuf = ta->recvbuf;
int channel = ta->channel % 65536; //send channel
int channel2 = cycling ? (ta->channel / 65536) - 1 : channel; //recv channel
int id = ta->thread_id;
long long int numschannels = ta->numchannels;
long long int numrchannels = ta->numrchannels;
long long int sendsize = totalsendsize / numschannels;
if(id < (totalsendsize % numschannels)) {
sendsize++;
}
#if SendRecvInputReport == 2
std::cout << "TDynEx(sendsize="<<sendsize<<",maxrecvsize="<<maxrecvsize<<",ch_send="<<channel<<",ch_recv="<<channel2<<",nc="<<numschannels<<"/"<<numrchannels<<std::endl;
#endif
unsigned char net_size_found[8], net_send_size[8];
long long int recvsizeall = -1;
size_t a, b;
long long int c,d;
a = b = 0;
c = d = 0;
// recvsize is initially set to the size of the long long int which holds the message size.
bool recv_settings_known = false; //this thread knows how much data may be received.
int mask = 0;
long long int offset_r = 0; //stores correct recv buffer offset for this thread.
/* Second: await the recvsize */
while(recvsize > d || sendsize > c) {
int mode = selectSockets(channel,channel2,mask);
/* (1.) Receiving is possible, but only done by thread 0 until we know more. */
if(mode%2 == 1) {
if(!recv_settings_known) {
int n = client[channel2]->irecv((char *)net_size_found+b,8-b);
b += n;
if(b == 8) { //recvsize data is now available.
size_t size_found = ::deserialize_size_t(net_size_found);
if (size_found > maxrecvsize) { //Would we want to do reallocs here???
std::cerr << "ERROR: DynEx recv size is greater than given constraint." << std::endl;
std::cerr << "(Size found = " << size_found << " bytes. Maxrecvsize = " << maxrecvsize << " bytes.)" << std::endl;
std::cerr << "(Channel: " << channel <<", Totalsendsize = "<< totalsendsize <<")" << std::endl;
std::cerr << "Going to sleep, so trace can be done. Press Ctrl-c to exit." << std::endl;
while(1) { sleep(1); }
}
recvsizeall = size_found;
if(id == 0) {
*(ta->dyn_recvsize) = size_found;
}
recvsize = recvsizeall / numrchannels;
if(id < (recvsizeall % numrchannels)) {
recvsize++;
}
if(id < numrchannels) {
offset_r = ((size_found / numrchannels) * id) + min(id,size_found % numrchannels);
recvbuf = &(ta->recvbuf[offset_r]);
}
recv_settings_known = true;
}
}
else {
int n = client[channel2]->irecv(recvbuf+d,min(tcpbuf_rsize,recvsize-d));
d += n;
#if MONITORING == 1
bytes_sent += n;
#endif
if(recvsize == d) { mask++; }
}
}