-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathnormStreamer.cpp
executable file
·2383 lines (2251 loc) · 88.3 KB
/
normStreamer.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
#include "normApi.h"
#include "protoSocket.h"
#include <stdio.h> // for printf(), etc
#include <stdlib.h> // for srand()
#include <string.h> // for strrchr(), memset(), etc
#include <sys/time.h> // for gettimeofday()
#include <arpa/inet.h> // for htons()
#include <fcntl.h> // for, well, fnctl()
#include <errno.h> // obvious child
#include <assert.h> // embarrassingly obvious
#include <sys/mman.h> // Memory Lock.
#include <sched.h> // Adjust scheduler (linux)
#include <sys/resource.h> // for setpriority() stuff
#ifdef LINUX
#include <sys/timerfd.h>
#endif // LINUX
const unsigned int LOOP_MAX = 1;
// Setting SHOOT_FIRST to non-zero means that an ACK request
// will be used to advance the acking "watermark" point
// with each message fully written to the transmit stream.
// The alternative "ack later" behavior waits to send a new
// ACK request until any pending flow control ACK requeset
// has completed. This latter approach favors throughput
// over timeliness of message delivery. I.e., lower data
// rate applications that are concerned with low-latency message
// delivery can potentially benefit from the "shoot first"
// behavior while very high throughput applications that want
// to "keep the pipe full as possible" can benefit from the
// "ack later" behavior. The difference between these behaviors,
// since ACK requests are cued for all messages when flow
// control is _not_ pending, is somewhat subtle and developers
// may want to assess both behaviors for their application.
// Additionally, limiting ACK request to flow control only is
// another possible approach as well as dynamically updating
// something like the "tx_stream_buffer_count" with each
// message ACK request initiated could be possible. The caution
// with the SHOOT_FIRST type strategies and high throughput is
// the application may end up "chasing" the ACK request until
// flow control buffer limits are reached and end up with
// "dead air" time. There are always tradeoffs!
//#define SHOOT_FIRST 0
class NormStreamer
{
public:
NormStreamer();
~NormStreamer();
// some day build these directly into NORM API
enum CCMode {NORM_FIXED, NORM_CC, NORM_CCE, NORM_CCL};
enum
{
MSG_HEADER_SIZE = 2, // Big Endian message length header size
MSG_SIZE_MAX = 65535 // (including length header)
};
void SetOutputFile(FILE* filePtr)
{
output_file = filePtr;
output_fd = fileno(filePtr);
}
void SetLoopback(bool state)
{
loopback = state;
if (NORM_SESSION_INVALID != norm_session)
{
NormSetMulticastLoopback(norm_session, state);
NormSetLoopback(norm_session, state); // XXX test code
}
}
void SetFtiInfo(bool state)
{
fti_info = state;
if (NORM_SESSION_INVALID != norm_session)
NormLimitObjectInfo(norm_session, state);
}
void SetAckEx(bool state)
{ack_ex = state;}
bool EnableUdpRelay(const char* relayAddr, unsigned short relayPort);
bool EnableUdpListener(unsigned short thePort, const char* groupAddr, const char * interfaceName);
bool UdpListenerEnabled() const
{return input_socket.IsOpen();}
bool UdpRelayEnabled() const
{return output_socket.IsOpen();}
int GetInputDescriptor() const
{return (input_socket.IsOpen() ? input_socket.GetHandle() : fileno(input_file));}
int GetOutputDescriptor() const
{return (output_socket.IsOpen() ? output_socket.GetHandle() : fileno(output_file));}
bool OpenNormSession(NormInstanceHandle instance,
const char* addr,
unsigned short port,
NormNodeId nodeId);
void CloseNormSession();
void SetNormCongestionControl(CCMode ccMode);
void SetFlushMode(NormFlushMode flushMode)
{flush_mode = flushMode;}
void SetNormTxRate(double bitsPerSecond)
{
assert(NORM_SESSION_INVALID != norm_session);
NormSetTxRate(norm_session, bitsPerSecond);
}
void SetNormMulticastInterface(const char* ifaceName)
{
assert(NORM_SESSION_INVALID != norm_session);
NormSetMulticastInterface(norm_session, ifaceName);
}
void SetNormMessageTrace(bool state)
{
assert(NORM_SESSION_INVALID != norm_session);
NormSetMessageTrace(norm_session, state);
}
void AddAckingNode(NormNodeId ackId)
{
assert(NORM_SESSION_INVALID != norm_session);
NormAddAckingNode(norm_session, ackId);
acking_node_count++;
norm_acking = true; // invoke ack-based flow control
}
void SetAutoAck(bool enable)
{
auto_ack = enable;
norm_acking = enable;
}
bool Start(bool sender, bool receiver);
void Stop()
{is_running = false;}
bool IsRunning() const
{return is_running;}
void HandleNormEvent(const NormEvent& event);
// Sender methods
int GetInputFile() const
{return input_fd;}
void SetInputReady()
{input_ready = true;}
bool InputReady() const
{return input_ready;}
bool InputNeeded() const
{return input_needed;}
void ReadInput();
void ReadInputSocket();
bool TxPending() const
{return (!input_needed && (input_index < input_msg_length));}
bool TxReady() const
{return (tx_ready && (!norm_acking || (tx_stream_buffer_count < tx_stream_buffer_max)));}
void SendData();
unsigned int WriteToStream(const char* buffer, unsigned int numBytes);
void FlushStream(bool eom, NormFlushMode flushMode);
// Receiver methods
bool RxNeeded() const
{return rx_needed;}
bool RxReady() const
{return rx_ready;}
void RecvData();
int GetOutputFile() const
{return output_fd;}
void SetOutputReady()
{output_ready = true;}
bool OutputReady() const
{return output_ready;}
bool OutputPending() const
{return (!rx_needed && (output_index < output_msg_length));}
void SetOutputBucketRate(double bitsPerSecond)
{
output_bucket_rate = bitsPerSecond / 8.0; // convert to bytes per second
output_bucket_interval = 1.0 / output_bucket_rate;
}
void SetOutputBucketDepth(unsigned int numBytes)
{output_bucket_depth = numBytes;}
unsigned int GetOutputBucketDepth() const
{return output_bucket_depth;}
double GetOutputBucketTimeout() const
{
if (0 != output_bucket_depth)
{
if (OutputPending())
{
unsigned int pendingBytes = output_msg_length - output_index;
if (pendingBytes > output_bucket_count)
{
return ((double)(pendingBytes - output_bucket_count)) * output_bucket_interval;
}
else
{
return 0.0;
}
}
else
{
return -1.0;
}
}
else
{
return 0.0;
}
}
double GetOutputBucketFillTime() const
{
return (output_bucket_count < output_bucket_depth) ?
((double)(output_bucket_depth - output_bucket_count)) * output_bucket_interval :
0.0;
}
bool OutputBucketReady() const
{
if (0 != output_bucket_depth)
{
unsigned int pendingBytes = output_msg_length - output_index;
return (output_bucket_count >= pendingBytes);
}
else
{
return true;
}
}
void CreditOutputBucket(double interval)
{
if (0 != output_bucket_depth)
{
output_bucket_count += interval * output_bucket_rate;
if (output_bucket_count > output_bucket_depth)
output_bucket_count = output_bucket_depth;
}
}
void WriteOutput();
void WriteOutputSocket();
void OmitHeader(bool state)
{omit_header = state;}
unsigned long GetInputByteCount() const
{return input_byte_count;}
unsigned long GetTxByteCount() const
{return tx_byte_count;}
// These can only be called post-OpenNormSession()
void SetSilentReceiver(bool state)
{NormSetSilentReceiver(norm_session, state);}
void SetTxLoss(double txloss)
{NormSetTxLoss(norm_session, txloss);}
void SetRxLoss(double rxloss)
{NormSetRxLoss(norm_session, rxloss);}
// Set the scheduler for running the app and norm threads.
static bool BoostPriority();
void SetSegmentSize(unsigned short segmentSize)
{segment_size = segmentSize;}
void SetBlockSize(unsigned short blockSize)
{block_size = blockSize;}
void SetNumParity(unsigned short numParity)
{num_parity = numParity;}
void SetAutoParity(unsigned short autoParity)
{auto_parity = autoParity;}
void SetStreamBufferSize(unsigned int value)
{stream_buffer_size = value;}
void SetTxSocketBufferSize(unsigned int value)
{tx_socket_buffer_size = value;}
void SetRxSocketBufferSize(unsigned int value)
{rx_socket_buffer_size = value;}
void SetInputSocketBufferSize(unsigned int value)
{input_socket_buffer_size = value;}
void SetOutputSocketBufferSize(unsigned int value)
{output_socket_buffer_size = value;}
void SetProbeTOS(UINT8 value)
{probe_tos = value;}
// Check that sequence numbers increase by one each time.
// Assumes that sequence number is 8- or 4-byte network-order first 8 bytes of buffer.
void CheckSequenceNumber(const char* buffer, const char* source);
void CheckSequenceNumber64(const char* buffer, const char* source);
void CheckSequenceNumber32(const char* buffer, const char* source);
void SetCheckSequence(unsigned int value) // 64 or 32
{check_sequence = value;}
private:
NormSessionHandle norm_session;
bool is_multicast;
UINT8 probe_tos;
bool loopback;
bool is_running;
// State variables for reading input messages for transmission
ProtoSocket input_socket; // optional UDP socket to "listen"
FILE* input_file;
int input_fd; // stdin by default
bool input_ready;
bool input_needed;
char input_buffer[MSG_SIZE_MAX];
unsigned int input_msg_length;
unsigned int input_index;
NormObjectHandle tx_stream;
bool tx_ready;
unsigned int tx_stream_buffer_max;
unsigned int tx_stream_buffer_threshold; // flow control threshold
unsigned int tx_stream_buffer_count;
unsigned int tx_stream_bytes_remain;
bool tx_watermark_pending;
bool norm_acking;
bool auto_ack;
unsigned int acking_node_count;
bool tx_ack_pending;
NormFlushMode flush_mode; // TBD - allow for "none", "passive", "active" options
bool fti_info;
bool ack_ex;
// Receive stream and state variables for writing received messages to output
NormObjectHandle rx_stream;
bool rx_ready;
bool rx_needed;
bool msg_sync;
double output_bucket_rate; // bytes per second
double output_bucket_interval; // seconds per byte
unsigned int output_bucket_depth; // bytes
unsigned int output_bucket_count; // bytes
ProtoSocket output_socket; // optional UDP socket for recv msg output
ProtoAddress relay_addr; // dest addr for recv msg relay
FILE* output_file;
int output_fd; // stdout by default
bool output_ready;
char output_buffer[MSG_SIZE_MAX];
unsigned int output_msg_length;
unsigned int output_index;
// These are some options mainly for testing purposes
bool omit_header; // if "true", receive message length header is _not_ written to output
bool rx_silent;
//double tx_loss;
unsigned long input_byte_count;
unsigned long tx_byte_count;
unsigned short segment_size;
unsigned short block_size;
unsigned short num_parity;
unsigned short auto_parity;
unsigned long stream_buffer_size;
unsigned int tx_socket_buffer_size;
unsigned int rx_socket_buffer_size;
unsigned int input_socket_buffer_size;
unsigned int output_socket_buffer_size;
unsigned int check_sequence;
uint64_t sequence_prev;
}; // end class NormStreamer
NormStreamer::NormStreamer()
: norm_session(NORM_SESSION_INVALID), is_multicast(false), probe_tos(0), loopback(false), is_running(false),
input_socket(ProtoSocket::UDP), input_file(stdin), input_fd(fileno(stdin)), input_ready(true),
input_needed(false), input_msg_length(0), input_index(0),
tx_stream (NORM_OBJECT_INVALID), tx_ready(true),
tx_stream_buffer_max(0), tx_stream_buffer_count(0), tx_stream_bytes_remain(0), tx_watermark_pending(false),
norm_acking(false), auto_ack(false), acking_node_count(0), tx_ack_pending(false), flush_mode(NORM_FLUSH_ACTIVE),
fti_info(false), ack_ex(false), rx_stream(NORM_OBJECT_INVALID), rx_ready(false), rx_needed(false), msg_sync(false),
output_bucket_rate(0.0), output_bucket_interval(0.0), output_bucket_depth(0), output_bucket_count(0),
output_socket(ProtoSocket::UDP), output_file(stdout), output_fd(fileno(stdout)), output_ready(true),
output_msg_length(0), output_index(0),
omit_header(false), rx_silent(false), input_byte_count(0), tx_byte_count(0),
segment_size(1398), block_size(64), num_parity(0), auto_parity(0),
stream_buffer_size(2*1024*1024),
tx_socket_buffer_size(0), rx_socket_buffer_size(0),
input_socket_buffer_size(0), output_socket_buffer_size(0),
check_sequence(0), sequence_prev(0)
{
}
NormStreamer::~NormStreamer()
{
}
bool NormStreamer::BoostPriority()
{
#ifdef LINUX
pid_t this_process = getpid() ;
int policy = SCHED_FIFO ;
int max_priority = sched_get_priority_max(policy) ;
struct sched_param schedule_parameters ;
memset((void*)&schedule_parameters, 0, sizeof(schedule_parameters)) ;
schedule_parameters.sched_priority = max_priority ;
int status = sched_setscheduler(this_process, policy, &schedule_parameters) ;
if (0 != status)
{
fprintf(stderr, "%s:=>sched_setscheduler failed (%d), %s\n", __PRETTY_FUNCTION__, errno, strerror(errno) ) ;
return false ;
}
else
{
fprintf(stderr, "%s:=>sched_setscheduler set priority to %d for process %u \n", __PRETTY_FUNCTION__, max_priority, this_process ) ;
}
#else
// (TBD) Do something differently if "pthread sched param"?
if (0 != setpriority(PRIO_PROCESS, getpid(), -20))
{
PLOG(PL_ERROR, "NormStreamer::BoostPriority() error: setpriority() error: %s\n", GetErrorString());
return false;
}
#endif // if/else LINUX
return true;
}
#ifndef ntohll
//Convert net-order to host-order.
uint64_t ntohll(uint64_t value)
{
static const int betest = 1 ;
union MyUnion
{
uint64_t i64;
uint32_t i32[2];
};
uint64_t rval = value;
bool host_is_little_endian = ( 1 == (int)(*(char*)&betest) ) ;
if ( host_is_little_endian )
{
MyUnion u;
u.i64 = value;
uint32_t temp = u.i32[0];
u.i32[0] = ntohl(u.i32[1]);
u.i32[1] = ntohl(temp);
rval = u.i64;
}
return rval ;
}
#endif // !nothll
void NormStreamer::CheckSequenceNumber64(const char* buffer, const char* source)
{
uint64_t temp;
memcpy((void*)&temp, (void*)buffer, sizeof(temp));
uint64_t sequence = ntohll(temp);
if (0 != sequence_prev)
{
int64_t delta = (int64_t)(sequence - sequence_prev);
if (1 != delta)
{
fprintf(stderr, "normStreamer: %s dropped %lu packets seq:%lu seq_prev:%lu\n",
source, (unsigned long)delta, (unsigned long)sequence,
(unsigned long)sequence_prev);
}
}
sequence_prev = sequence;
} // end NormStreamer::CheckSequenceNumber64()
void NormStreamer::CheckSequenceNumber32(const char* buffer, const char* source)
{
uint32_t temp;
memcpy((void*)&temp, (void*)buffer, sizeof(temp));
uint32_t sequence = ntohll(temp);
if (0 != sequence_prev)
{
int32_t delta = (int32_t)(sequence - sequence_prev);
if (1 != delta)
{
fprintf(stderr, "normStreamer: %s dropped %lu packets seq:%lu seq_prev:%lu\n",
source, (unsigned long)delta, (unsigned long)sequence,
(unsigned long)sequence_prev);
}
}
sequence_prev = sequence;
} // end NormStreamer::CheckSequenceNumber32()
void NormStreamer::CheckSequenceNumber(const char* buffer, const char* source)
{
switch (check_sequence)
{
case 32:
CheckSequenceNumber32(buffer, source);
break;
case 64:
CheckSequenceNumber64(buffer, source) ;
break;
default:
break;
}
} // end NormStreamer::CheckSequenceNumber()
bool NormStreamer::EnableUdpRelay(const char* relayAddr, unsigned short relayPort)
{
if (!output_socket.Open())
{
fprintf(stderr, "normStreamer error: unable to open 'relay' socket\n");
return false ;
}
if (!output_socket.SetTxBufferSize(output_socket_buffer_size))
{
fprintf(stderr, "normStreamer warning: unable to set desired 'relay' socket buffer size (retrieved value:%u)\n",
output_socket.GetTxBufferSize());
}
if (!relay_addr.ResolveFromString(relayAddr))
{
fprintf(stderr, "normStreamer error: invalid relay address\n");
output_socket.Close();
return false;
}
relay_addr.SetPort(relayPort); // TBD - validate port number??
return true;
} // end bool EnableUdpRelay()
bool NormStreamer::EnableUdpListener(unsigned short thePort, const char* groupAddr, const char * interfaceName)
{
if (!input_socket.Open(thePort))
{
fprintf(stderr, "normStreamer error: unable to open 'listen' socket on port %hu\n", thePort);
return false;
}
if (!input_socket.SetRxBufferSize(input_socket_buffer_size))
{
fprintf(stderr, "normStreamer error: unable to set desired 'listen' socket buffer size\n");
return false;
}
if (NULL != groupAddr)
{
ProtoAddress addr;
if (!addr.ResolveFromString(groupAddr) || (!addr.IsMulticast()))
{
fprintf(stderr, "normStreamer error: invalid 'listen' group address\n");
input_socket.Close();
return false ;
}
if (!input_socket.JoinGroup(addr, interfaceName))
{
fprintf(stderr, "normStreamer error: unable to join 'listen' group address\n");
input_socket.Close();
return false;
}
}
return true;
} // end NormStreamer::EnableUdpListener()
bool NormStreamer::OpenNormSession(NormInstanceHandle instance, const char* addr, unsigned short port, NormNodeId nodeId)
{
if (NormIsUnicastAddress(addr))
is_multicast = false;
else
is_multicast = true;
norm_session = NormCreateSession(instance, addr, port, nodeId);
if (NORM_SESSION_INVALID == norm_session)
{
fprintf(stderr, "normStreamer error: unable to create NORM session\n");
return false;
}
if (is_multicast)
{
NormSetRxPortReuse(norm_session, true);
if (loopback)
{
NormSetMulticastLoopback(norm_session, true);
}
}
NormSetLoopback(norm_session, loopback);
// Set some default parameters (maybe we should put parameter setting in Start())
NormSetDefaultSyncPolicy(norm_session, NORM_SYNC_CURRENT);
if (!is_multicast)
NormSetDefaultUnicastNack(norm_session, true);
NormSetTxRobustFactor(norm_session, 20);
NormSetGrttProbingTOS(norm_session, probe_tos);
NormSetFragmentation(norm_session, true); // so that IP ID gets set for SMF DPD
return true;
} // end NormStreamer::OpenNormSession()
void NormStreamer::CloseNormSession()
{
if (NORM_SESSION_INVALID == norm_session) return;
NormDestroySession(norm_session);
norm_session = NORM_SESSION_INVALID;
} // end NormStreamer::CloseNormSession()
void NormStreamer::SetNormCongestionControl(CCMode ccMode)
{
assert(NORM_SESSION_INVALID != norm_session);
switch (ccMode)
{
case NORM_CC: // default TCP-friendly congestion control
NormSetEcnSupport(norm_session, false, false, false);
break;
case NORM_CCE: // "wireless-ready" ECN-only congestion control
NormSetEcnSupport(norm_session, true, true);
break;
case NORM_CCL: // "loss tolerant", non-ECN congestion control
NormSetEcnSupport(norm_session, false, false, true);
break;
case NORM_FIXED: // "fixed" constant data rate
NormSetEcnSupport(norm_session, false, false, false);
break;
}
if (NORM_FIXED != ccMode)
NormSetCongestionControl(norm_session, true);
else
NormSetCongestionControl(norm_session, false);
} // end NormStreamer::SetNormCongestionControl()
bool NormStreamer::Start(bool sender, bool receiver)
{
// Note the session NORM buffer size is set the same s stream_buffer_size
unsigned int bufferSize = stream_buffer_size;
if (receiver)
{
if (!NormPreallocateRemoteSender(norm_session, bufferSize, segment_size, block_size, num_parity, stream_buffer_size))
fprintf(stderr, "normStreamer warning: unable to preallocate remote sender\n");
fprintf(stderr, "normStreamer: receiver ready.\n");
if (!NormStartReceiver(norm_session, bufferSize))
{
fprintf(stderr, "normStreamer error: unable to start NORM receiver\n");
return false;
}
if (0 != mlockall(MCL_CURRENT | MCL_FUTURE))
fprintf(stderr, "normStreamer error: failed to lock memory for receiver.\n");
if (0 != rx_socket_buffer_size)
NormSetRxSocketBuffer(norm_session, rx_socket_buffer_size);
rx_needed = true;
rx_ready = false;
}
if (sender)
{
NormSetGrttEstimate(norm_session, 0.001);
//NormSetGrttMax(norm_session, 0.100);
NormSetBackoffFactor(norm_session, 0);
if (norm_acking)
{
// ack-based flow control enabled on command-line,
// so disable timer-based flow control
NormSetFlowControl(norm_session, 0.0);
NormTrackingStatus trackingMode = auto_ack? NORM_TRACK_RECEIVERS : NORM_TRACK_NONE;
NormSetAutoAckingNodes(norm_session, trackingMode);
if (auto_ack && (0 == acking_node_count))
{
// This allows for the receivrer(s) to start after the sender
// as the sender will persistently send ack requests until
// a receiver responds.
NormAddAckingNode(norm_session, NORM_NODE_NONE);
}
}
// Pick a random instance id for now
struct timeval currentTime;
gettimeofday(¤tTime, NULL);
srand(currentTime.tv_usec); // seed random number generator
NormSessionId instanceId = (NormSessionId)rand();
if (fti_info)
NormLimitObjectInfo(norm_session, true);
if (!NormStartSender(norm_session, instanceId, bufferSize, segment_size, block_size, num_parity))
{
fprintf(stderr, "normStreamer error: unable to start NORM sender\n");
if (receiver) NormStopReceiver(norm_session);
return false;
}
if (auto_parity > 0)
NormSetAutoParity(norm_session, auto_parity < num_parity ? auto_parity : num_parity);
if (0 != tx_socket_buffer_size)
NormSetTxSocketBuffer(norm_session, tx_socket_buffer_size);
if (NORM_OBJECT_INVALID == (tx_stream = NormStreamOpen(norm_session, stream_buffer_size)))
{
fprintf(stderr, "normStreamer error: unable to open NORM tx stream\n");
NormStopSender(norm_session);
if (receiver) NormStopReceiver(norm_session);
return false;
}
else
{
if (0 != mlockall(MCL_CURRENT|MCL_FUTURE))
fprintf(stderr, "normStreamer warning: failed to lock memory for sender.\n");
}
tx_stream_buffer_max = NormGetStreamBufferSegmentCount(bufferSize, segment_size, block_size);
tx_stream_buffer_max -= block_size; // a little safety margin (perhaps not necessary)
tx_stream_buffer_threshold = tx_stream_buffer_max / 8;
tx_stream_buffer_count = 0;
tx_stream_bytes_remain = 0;
tx_watermark_pending = false;
tx_ack_pending = false;
tx_ready = true;
input_index = input_msg_length = 0;
input_needed = true;
input_ready = true;
}
is_running = true;
return true;
} // end NormStreamer::Start();
void NormStreamer::ReadInputSocket()
{
unsigned int loopCount = 0;
//NormSuspendInstance(NormGetInstance(norm_session));
while (input_needed && input_ready && (loopCount < LOOP_MAX))
{
loopCount++;
unsigned int numBytes = MSG_SIZE_MAX - MSG_HEADER_SIZE;
ProtoAddress srcAddr;
if (input_socket.RecvFrom(input_buffer+MSG_HEADER_SIZE, numBytes, srcAddr))
{
if (0 == numBytes)
{
input_ready = false;
break;
}
input_index = 0;
input_msg_length = numBytes + MSG_HEADER_SIZE;
input_byte_count += input_msg_length;
unsigned short msgSize = input_msg_length;;
msgSize = htons(msgSize);
memcpy(input_buffer, &msgSize, MSG_HEADER_SIZE);
input_needed = false;
if (TxReady()) SendData();
}
else
{
// TBD - handle error?
input_ready = false;
}
}
//NormResumeInstance(NormGetInstance(norm_session));
} // end NormStreamer::ReadInputSocket()
void NormStreamer::ReadInput()
{
if (UdpListenerEnabled()) return ReadInputSocket();
// The loop count makes sure we don't spend too much time here
// before going back to the main loop to handle NORM events, etc
unsigned int loopCount = 0;
//NormSuspendInstance(NormGetInstance(norm_session));
while (input_needed && input_ready && (loopCount < LOOP_MAX))
{
loopCount++;
//if (100 == loopCount)
// fprintf(stderr, "normStreamer ReadInput() loop count max reached\n");
unsigned int numBytes;
if (input_index < MSG_HEADER_SIZE)
{
// Reading message length header for next message to send
numBytes = MSG_HEADER_SIZE - input_index;
}
else
{
// Reading message body
assert(input_index < input_msg_length);
numBytes = input_msg_length - input_index;
}
TRACE("reading STDIN ...\n");
ssize_t result = read(input_fd, input_buffer + input_index, numBytes);
TRACE(" result: %d\n", (int)result);
if (result > 0)
{
input_index += result;
input_byte_count += result;
if (MSG_HEADER_SIZE == input_index)
{
// We have now read the message size header
// TBD - support other message header formats?
// (for now, assume 2-byte message length header)
uint16_t msgSize ;
memcpy(&msgSize, input_buffer, MSG_HEADER_SIZE);
msgSize = ntohs(msgSize);
input_msg_length = msgSize;
}
else if (input_index == input_msg_length)
{
// Message input complete
input_index = 0; // reset index for transmission phase
input_needed = false;
if (TxReady()) SendData();
}
else
{
// Still need more input
// (wait for next input notification to read more)
input_ready = false;
}
}
else if (0 == result)
{
// end-of-file reached, TBD - trigger final flushing and wrap-up
fprintf(stderr, "normStreamer: input end-of-file detected ...\n");
NormStreamClose(tx_stream, true);
if (norm_acking)
{
if (ack_ex)
{
const char* req = "Hello, acker";
NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1, true);
}
else
{
NormSetWatermark(norm_session, tx_stream, true);
}
tx_ack_pending = false;
}
input_needed = false;
}
else
{
switch (errno)
{
case EINTR:
continue; // interrupted, try again
case EAGAIN:
// input starved, wait for next notification
input_ready = false;
break;
default:
// TBD - handle this better
perror("normStreamer error reading input");
break;
}
break;
}
} // end while (input_needed && input_ready)
//NormResumeInstance(NormGetInstance(norm_session));
} // end NormStreamer::ReadInput()
void NormStreamer::SendData()
{
while (TxReady() && !input_needed)
{
// Note WriteToStream() or FlushStream() will set "tx_ready" to
// false upon flow control thus negating TxReady() status
assert(input_index < input_msg_length);
assert(input_msg_length);
if ((0 != check_sequence) && (0 == input_index))
CheckSequenceNumber(input_buffer+MSG_HEADER_SIZE, __func__);
input_index += WriteToStream(input_buffer + input_index, input_msg_length - input_index);
if (input_index == input_msg_length)
{
// Complete message was sent, so set eom and optionally flush
if (NORM_FLUSH_NONE != flush_mode)
FlushStream(true, flush_mode);
else
NormStreamMarkEom(tx_stream);
input_index = input_msg_length = 0;
input_needed = true;
}
else
{
//fprintf(stderr, "SendData() impeded by flow control\n");
}
} // end while (TxReady() && !input_needed)
} // end NormStreamer::SendData()
unsigned int NormStreamer::WriteToStream(const char* buffer, unsigned int numBytes)
{
unsigned int bytesWritten;
if (norm_acking)
{
// This method uses NormStreamWrite(), but limits writes by explicit ACK-based flow control status
if (tx_stream_buffer_count < tx_stream_buffer_max)
{
// 1) How many buffer bytes are available?
unsigned int bytesAvailable = segment_size * (tx_stream_buffer_max - tx_stream_buffer_count);
bytesAvailable -= tx_stream_bytes_remain; // unflushed segment portion
if (bytesAvailable < numBytes) numBytes = bytesAvailable;
assert(numBytes);
// 2) Write to the stream
bytesWritten = NormStreamWrite(tx_stream, buffer, numBytes);
tx_byte_count += bytesWritten;
// 3) Update "tx_stream_buffer_count" accordingly
unsigned int totalBytes = bytesWritten + tx_stream_bytes_remain;
unsigned int numSegments = totalBytes / segment_size;
tx_stream_bytes_remain = totalBytes % segment_size;
tx_stream_buffer_count += numSegments;
//assert(bytesWritten == numBytes); // this could fail if timer-based flow control is left enabled
// 3) Check if we need to issue a watermark ACK request?
if (!tx_watermark_pending && (tx_stream_buffer_count >= tx_stream_buffer_threshold))
{
// Initiate flow control ACK request
//fprintf(stderr, "write-initiated flow control ACK REQUEST\n");
if (ack_ex)
{
const char* req = "Hello, acker";
NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1);//, true);
}
else
{
NormSetWatermark(norm_session, tx_stream);//, true);
}
tx_watermark_pending = true;
tx_ack_pending = false;
}
}
else
{
fprintf(stderr, "normStreamer: sender flow control limited\n");
return 0;
}
}
else
{
bytesWritten = NormStreamWrite(tx_stream, buffer, numBytes);
tx_byte_count += bytesWritten;
}
if (bytesWritten != numBytes) //NormStreamWrite() was (at least partially) blocked
{
//fprintf(stderr, "NormStreamWrite() blocked by flow control ...\n");
tx_ready = false;
}
return bytesWritten;
} // end NormStreamer::WriteToStream()
void NormStreamer::FlushStream(bool eom, NormFlushMode flushMode)
{
if (norm_acking)
{
bool setWatermark = false;
if (0 != tx_stream_bytes_remain)
{
// The flush will force the runt segment out, so we increment our buffer usage count
// (and initiate flow control watermark ack request if buffer mid-point threshold exceeded
tx_stream_buffer_count++;
tx_stream_bytes_remain = 0;
if (!tx_watermark_pending && (tx_stream_buffer_count >= tx_stream_buffer_threshold))
{
setWatermark = true;
tx_watermark_pending = true;
//fprintf(stderr, "flush-initiated flow control ACK REQUEST\n");
}
}
// The check for "tx_watermark_pending" here prevents a new watermark
// ack request from being set until the pending flow control ack is
// received. This favors avoiding dead air time over saving "chattiness"
if (setWatermark)
{
// Flush passive since watermark will invoke active request
// (TBD - do non-acking nodes NACK to watermark when not ack target?)
NormStreamFlush(tx_stream, eom, NORM_FLUSH_PASSIVE);
}
else if (tx_watermark_pending)
{
// Pre-existing pending flow control watermark ack request
#if SHOOT_FIRST
// Go ahead and set a fresh watermark
// TBD - not sure this mode works properly ... may need to
// keep track of unacknowledged byte count and decrement accordingly
// when ack arrives
NormStreamFlush(tx_stream, eom, NORM_FLUSH_PASSIVE);
setWatermark = true;
#else // ACK_LATER
// Wait until flow control ACK is received before issuing another ACK request
NormStreamFlush(tx_stream, eom, flushMode);
tx_ack_pending = true; // will call NormSetWatermark() upon flow control ack completion
#endif
}
else
{
// Since we're acking, use active ack request in lieu of active flush
NormStreamFlush(tx_stream, eom, NORM_FLUSH_PASSIVE);
setWatermark = true;
}
if (setWatermark)
{
if (ack_ex)
{
const char* req = "Hello, acker";
NormSetWatermarkEx(norm_session, tx_stream, req, strlen(req) + 1, true);
}
else
{
NormSetWatermark(norm_session, tx_stream, true);
}
tx_ack_pending = false;
}
}
else
{
NormStreamFlush(tx_stream, eom, flushMode);
}
} // end NormStreamer::FlushStream()
void NormStreamer::RecvData()
{