forked from facebook/wdt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReceiverThread.cpp
1067 lines (1000 loc) · 37.6 KB
/
ReceiverThread.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
/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <wdt/ReceiverThread.h>
#include <folly/Conv.h>
#include <folly/Memory.h>
#include <folly/ScopeGuard.h>
#include <folly/String.h>
#include <folly/hash/Checksum.h>
#include <folly/lang/Bits.h>
#include <wdt/util/FileWriter.h>
namespace facebook {
namespace wdt {
const static int kTimeoutBufferMillis = 1000;
const static int kWaitTimeoutFactor = 5;
std::ostream &operator<<(std::ostream &os,
const ReceiverThread &receiverThread) {
os << "Thread[" << receiverThread.threadIndex_
<< ", port: " << receiverThread.socket_->getPort() << "] ";
return os;
}
int64_t readAtLeast(IServerSocket &s, char *buf, int64_t max, int64_t atLeast,
int64_t len) {
WVLOG(4) << "readAtLeast len " << len << " max " << max << " atLeast "
<< atLeast << " from " << s.getFd();
WDT_CHECK_GE(len, 0);
WDT_CHECK_GT(atLeast, 0);
WDT_CHECK_LE(atLeast, max);
int count = 0;
while (len < atLeast) {
// because we want to process data as soon as it arrives, tryFull option for
// read is false
int64_t n = s.read(buf + len, max - len, false);
if (n < 0) {
WPLOG(ERROR) << "Read error on " << s.getPort() << " after " << count;
if (len) {
return len;
} else {
return n;
}
}
if (n == 0) {
WVLOG(2) << "Eof on " << s.getPort() << " after " << count << " reads "
<< "got " << len;
return len;
}
len += n;
count++;
}
WVLOG(3) << "Took " << count << " reads to get " << len
<< " from fd : " << s.getFd();
return len;
}
int64_t readAtMost(IServerSocket &s, char *buf, int64_t max, int64_t atMost) {
const int64_t target = atMost < max ? atMost : max;
WVLOG(3) << "readAtMost target " << target;
// because we want to process data as soon as it arrives, tryFull option for
// read is false
int64_t n = s.read(buf, target, false);
if (n < 0) {
WPLOG(ERROR) << "Read error on " << s.getPort() << " target " << target;
return n;
}
if (n == 0) {
WLOG(WARNING) << "Eof on " << s.getFd();
return n;
}
WVLOG(3) << "readAtMost " << n << " / " << atMost << " from " << s.getFd();
return n;
}
const ReceiverThread::StateFunction ReceiverThread::stateMap_[] = {
&ReceiverThread::listen,
&ReceiverThread::acceptFirstConnection,
&ReceiverThread::acceptWithTimeout,
&ReceiverThread::sendLocalCheckpoint,
&ReceiverThread::readNextCmd,
&ReceiverThread::processFileCmd,
&ReceiverThread::processSettingsCmd,
&ReceiverThread::processDoneCmd,
&ReceiverThread::processSizeCmd,
&ReceiverThread::sendFileChunks,
&ReceiverThread::sendGlobalCheckpoint,
&ReceiverThread::sendDoneCmd,
&ReceiverThread::sendAbortCmd,
&ReceiverThread::waitForFinishOrNewCheckpoint,
&ReceiverThread::finishWithError};
ReceiverThread::ReceiverThread(Receiver *wdtParent, int threadIndex,
int32_t port, ThreadsController *controller)
: WdtThread(wdtParent->options_, threadIndex, port,
wdtParent->getProtocolVersion(), controller),
wdtParent_(wdtParent) {
controller_->registerThread(threadIndex_);
threadCtx_->setAbortChecker(&wdtParent_->abortCheckerCallback_);
}
/**LISTEN STATE***/
ReceiverState ReceiverThread::listen() {
WTVLOG(1) << "entered LISTEN state";
const bool doActualWrites = !options_.skip_writes;
int32_t port = socket_->getPort();
WVLOG(1) << "Server Thread for port " << port << " with backlog "
<< socket_->getBackLog() << " on " << wdtParent_->getDirectory()
<< " writes = " << doActualWrites;
for (int retry = 1; retry < options_.max_retries; ++retry) {
ErrorCode code = socket_->listen();
if (code == OK) {
break;
} else if (code == CONN_ERROR) {
threadStats_.setLocalErrorCode(code);
return FINISH_WITH_ERROR;
}
WTLOG(INFO) << "Sleeping after failed attempt " << retry;
/* sleep override */
usleep(options_.sleep_millis * 1000);
}
// one more/last try (stays true if it worked above)
if (socket_->listen() != OK) {
WTLOG(ERROR) << "Unable to listen/bind despite retries";
threadStats_.setLocalErrorCode(CONN_ERROR);
return FINISH_WITH_ERROR;
}
return ACCEPT_FIRST_CONNECTION;
}
/***ACCEPT_FIRST_CONNECTION***/
ReceiverState ReceiverThread::acceptFirstConnection() {
WTVLOG(1) << "entered ACCEPT_FIRST_CONNECTION state";
reset();
socket_->closeNoCheck();
auto timeout = options_.accept_timeout_millis;
int acceptAttempts = 0;
while (true) {
// Move to timeout state if some other thread was successful
// in getting a connection
if (wdtParent_->hasNewTransferStarted()) {
return ACCEPT_WITH_TIMEOUT;
}
switch (wdtParent_->getAcceptMode()) {
case Receiver::AcceptMode::ACCEPT_WITH_RETRIES: {
if (acceptAttempts >= options_.max_accept_retries) {
WTLOG(ERROR) << "Unable to accept after " << acceptAttempts
<< " attempts";
threadStats_.setLocalErrorCode(CONN_ERROR);
return FINISH_WITH_ERROR;
}
break;
}
case Receiver::AcceptMode::ACCEPT_FOREVER: {
WTVLOG(2) << "Receiver is configured to accept for-ever";
break;
}
case Receiver::AcceptMode::STOP_ACCEPTING: {
WTLOG(ERROR) << "Receiver is asked to stop accepting, attempts : "
<< acceptAttempts;
threadStats_.setLocalErrorCode(CONN_ERROR);
return FINISH_WITH_ERROR;
}
}
if (wdtParent_->getCurAbortCode() != OK) {
WTLOG(ERROR) << "Thread marked to abort while trying to accept "
<< "first connection. Num attempts " << acceptAttempts;
threadStats_.setLocalErrorCode(ABORT);
return FINISH_WITH_ERROR;
}
ErrorCode code =
socket_->acceptNextConnection(timeout, curConnectionVerified_);
if (code == OK) {
break;
}
++acceptAttempts;
}
// Make the parent start new global session. This is executed
// only by the first thread that calls this function
controller_->executeAtStart(
[&]() { wdtParent_->startNewGlobalSession(socket_->getPeerIp()); });
return READ_NEXT_CMD;
}
/***ACCEPT_WITH_TIMEOUT STATE***/
ReceiverState ReceiverThread::acceptWithTimeout() {
WTLOG(INFO) << "entered ACCEPT_WITH_TIMEOUT state";
// check socket status
ErrorCode socketErrCode = socket_->getNonRetryableErrCode();
if (socketErrCode != OK) {
WTLOG(ERROR) << "Socket has non-retryable error "
<< errorCodeToStr(socketErrCode);
threadStats_.setLocalErrorCode(socketErrCode);
return END;
}
socket_->closeNoCheck();
blocksWaitingVerification_.clear();
auto timeout = options_.accept_window_millis;
if (senderReadTimeout_ > 0) {
// transfer is in progress and we have already got sender settings
timeout = std::max(senderReadTimeout_, senderWriteTimeout_) +
kTimeoutBufferMillis;
}
ErrorCode code =
socket_->acceptNextConnection(timeout, curConnectionVerified_);
curConnectionVerified_ = false;
if (code != OK) {
WTLOG(ERROR) << "accept() failed with error " << errorCodeToStr(code)
<< " timeout " << timeout;
threadStats_.setLocalErrorCode(code);
return FINISH_WITH_ERROR;
}
numRead_ = off_ = 0;
pendingCheckpointIndex_ = checkpointIndex_;
ReceiverState nextState = READ_NEXT_CMD;
if (threadStats_.getLocalErrorCode() != OK) {
nextState = SEND_LOCAL_CHECKPOINT;
}
// reset thread status
threadStats_.setLocalErrorCode(OK);
return nextState;
}
/***SEND_LOCAL_CHECKPOINT STATE***/
ReceiverState ReceiverThread::sendLocalCheckpoint() {
WTLOG(INFO) << "entered SEND_LOCAL_CHECKPOINT state " << checkpoint_;
std::vector<Checkpoint> checkpoints;
checkpoints.emplace_back(checkpoint_);
int64_t off = 0;
const int checkpointLen =
Protocol::getMaxLocalCheckpointLength(threadProtocolVersion_);
Protocol::encodeCheckpoints(threadProtocolVersion_, buf_, off, checkpointLen,
checkpoints);
int written = socket_->write(buf_, checkpointLen);
if (written != checkpointLen) {
WTLOG(ERROR) << "unable to write local checkpoint. write mismatch "
<< checkpointLen << " " << written;
threadStats_.setLocalErrorCode(SOCKET_WRITE_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
threadStats_.addHeaderBytes(checkpointLen);
return READ_NEXT_CMD;
}
/***READ_NEXT_CMD***/
ReceiverState ReceiverThread::readNextCmd() {
WTVLOG(1) << "entered READ_NEXT_CMD state";
oldOffset_ = off_;
// TODO: we shouldn't have off_ here and buffer/size inside buffer.
numRead_ = readAtLeast(*socket_, buf_ + off_, bufSize_ - off_,
Protocol::kMinBufLength, numRead_);
if (numRead_ < Protocol::kMinBufLength) {
WTLOG(ERROR) << "socket read failure " << Protocol::kMinBufLength << " "
<< numRead_;
threadStats_.setLocalErrorCode(SOCKET_READ_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
Protocol::CMD_MAGIC cmd = (Protocol::CMD_MAGIC)buf_[off_++];
if (cmd == Protocol::DONE_CMD) {
return PROCESS_DONE_CMD;
}
if (cmd == Protocol::FILE_CMD) {
return PROCESS_FILE_CMD;
}
if (cmd == Protocol::SETTINGS_CMD) {
return PROCESS_SETTINGS_CMD;
}
if (cmd == Protocol::SIZE_CMD) {
return PROCESS_SIZE_CMD;
}
WTLOG(ERROR) << "received an unknown cmd " << cmd;
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
/***PROCESS_SETTINGS_CMD***/
ReceiverState ReceiverThread::processSettingsCmd() {
WTVLOG(1) << "entered PROCESS_SETTINGS_CMD state";
Settings settings;
int senderProtocolVersion;
bool success = Protocol::decodeVersion(
buf_, off_, oldOffset_ + Protocol::kMaxVersion, senderProtocolVersion);
if (!success) {
WTLOG(ERROR) << "Unable to decode version " << threadIndex_;
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
if (senderProtocolVersion != threadProtocolVersion_) {
WTLOG(WARNING) << "Receiver and sender protocol version mismatch "
<< senderProtocolVersion << " " << threadProtocolVersion_;
int negotiatedProtocol = Protocol::negotiateProtocol(
senderProtocolVersion, threadProtocolVersion_);
if (negotiatedProtocol == 0) {
WTLOG(WARNING) << "Can not support sender with version "
<< senderProtocolVersion << ", aborting!";
threadStats_.setLocalErrorCode(VERSION_INCOMPATIBLE);
return SEND_ABORT_CMD;
} else {
WLOG_IF(INFO, threadProtocolVersion_ != negotiatedProtocol)
<< *this << "Changing receiver protocol version to "
<< negotiatedProtocol;
threadProtocolVersion_ = negotiatedProtocol;
if (negotiatedProtocol != senderProtocolVersion) {
threadStats_.setLocalErrorCode(VERSION_MISMATCH);
return SEND_ABORT_CMD;
}
}
}
if (threadProtocolVersion_ <
Protocol::PERIODIC_ENCRYPTION_IV_CHANGE_VERSION) {
socket_->disableIvChange();
}
success = Protocol::decodeSettings(
threadProtocolVersion_, buf_, off_,
oldOffset_ + Protocol::kMaxVersion + Protocol::kMaxSettings, settings);
if (!success) {
WTLOG(ERROR) << "Unable to decode settings cmd ";
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
auto senderId = settings.transferId;
auto transferId = wdtParent_->getTransferId();
if (transferId != senderId) {
WTLOG(ERROR) << "Receiver and sender id mismatch " << senderId << " "
<< transferId;
threadStats_.setLocalErrorCode(ID_MISMATCH);
return SEND_ABORT_CMD;
}
senderReadTimeout_ = settings.readTimeoutMillis;
senderWriteTimeout_ = settings.writeTimeoutMillis;
isBlockMode_ = !settings.blockModeDisabled;
enableHeartBeat_ = settings.enableHeartBeat;
if (!enableHeartBeat_) {
WTLOG(INFO) << "Disabling heart-beat as sender does not support it";
}
curConnectionVerified_ = true;
// determine footer type
if (settings.enableChecksum) {
footerType_ = CHECKSUM_FOOTER;
} else {
footerType_ = NO_FOOTER;
}
if (settings.sendFileChunks) {
// We only move to SEND_FILE_CHUNKS state, if download resumption is enabled
// in the sender side
numRead_ = off_ = 0;
return SEND_FILE_CHUNKS;
}
auto msgLen = off_ - oldOffset_;
numRead_ -= msgLen;
return READ_NEXT_CMD;
}
void ReceiverThread::sendHeartBeat() {
if (!enableHeartBeat_) {
return;
}
const auto now = Clock::now();
const int timeSinceLastHeartBeatMs = durationMillis(now - lastHeartBeatTime_);
const int heartBeatIntervalMs = (senderReadTimeout_ / kWaitTimeoutFactor);
if (timeSinceLastHeartBeatMs <= heartBeatIntervalMs) {
return;
}
lastHeartBeatTime_ = now;
// time to send a heart beat
char buf = Protocol::HEART_BEAT_CMD;
const int written = socket_->write(&buf, 1);
if (written != 1) {
WTLOG(WARNING) << "Failed to send heart-beat " << written;
}
}
/***PROCESS_FILE_CMD***/
ReceiverState ReceiverThread::processFileCmd() {
WTVLOG(1) << "entered PROCESS_FILE_CMD state";
// following block needs to be executed for the first file cmd. There is no
// harm in executing it more than once. number of blocks equal to 0 is a good
// approximation for first file cmd. Did not want to introduce another boolean
if (options_.enable_download_resumption && threadStats_.getNumBlocks() == 0) {
auto sendChunksFunnel = controller_->getFunnel(SEND_FILE_CHUNKS_FUNNEL);
auto state = sendChunksFunnel->getStatus();
if (state == FUNNEL_START) {
// sender is not in resumption mode
wdtParent_->addTransferLogHeader(isBlockMode_,
/* sender not resuming */ false);
sendChunksFunnel->notifySuccess();
}
}
checkpoint_.resetLastBlockDetails();
BlockDetails blockDetails;
auto guard = folly::makeGuard([&] {
if (threadStats_.getLocalErrorCode() != OK) {
threadStats_.incrFailedAttempts();
}
});
ErrorCode transferStatus = (ErrorCode)buf_[off_++];
if (transferStatus != OK) {
// TODO: use this status information to implement fail fast mode
WTVLOG(1) << "sender entered into error state "
<< errorCodeToStr(transferStatus);
}
int16_t headerLen = folly::loadUnaligned<int16_t>(buf_ + off_);
headerLen = folly::Endian::little(headerLen);
if (headerLen <= 0) {
WTLOG(ERROR) << "Header length must be positive " << headerLen;
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
WVLOG(2) << "Processing FILE_CMD, header len " << headerLen;
sendHeartBeat();
if (headerLen > numRead_) {
int64_t end = oldOffset_ + numRead_;
numRead_ =
readAtLeast(*socket_, buf_ + end, bufSize_ - end, headerLen, numRead_);
}
if (numRead_ < headerLen) {
WTLOG(ERROR) << "Unable to read full header " << headerLen << " "
<< numRead_;
threadStats_.setLocalErrorCode(SOCKET_READ_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
off_ += sizeof(int16_t);
bool success = Protocol::decodeHeader(threadProtocolVersion_, buf_, off_,
numRead_ + oldOffset_, blockDetails);
int64_t headerBytes = off_ - oldOffset_;
// transferred header length must match decoded header length
if (headerLen != headerBytes) {
WTLOG(ERROR) << "Decoded header length: " << headerBytes
<< ", transferred header length: " << headerBytes
<< ", they should be equal.";
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
threadStats_.addHeaderBytes(headerBytes);
threadStats_.addEffectiveBytes(headerBytes, 0);
if (!success) {
WTLOG(ERROR) << "Error decoding at"
<< " ooff:" << oldOffset_ << " off_: " << off_
<< " numRead_: " << numRead_;
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
if (blockDetails.allocationStatus == TO_BE_DELETED &&
(blockDetails.fileSize != 0 || blockDetails.dataSize != 0)) {
WTLOG(ERROR) << "Invalid file header, file to be deleted, but "
"file-size/block-size not zero "
<< blockDetails.fileName << " file-size "
<< blockDetails.fileSize << " block-size "
<< blockDetails.dataSize;
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
// received a well formed file cmd, apply the pending checkpoint update
checkpointIndex_ = pendingCheckpointIndex_;
WTVLOG(1) << "Read id:" << blockDetails.fileName
<< " size:" << blockDetails.dataSize << " ooff:" << oldOffset_
<< " off_: " << off_ << " numRead_: " << numRead_;
auto &fileCreator = wdtParent_->getFileCreator();
FileWriter writer(*threadCtx_, &blockDetails, fileCreator.get());
const auto encryptionType = socket_->getEncryptionType();
auto writtenGuard = folly::makeGuard([&] {
if (!encryptionTypeToTagLen(encryptionType) && footerType_ == NO_FOOTER) {
// if encryption doesn't have tag verification and checksum verification
// is disabled, we can consider bytes received before connection break as
// valid
checkpoint_.setLastBlockDetails(blockDetails.seqId, blockDetails.offset,
writer.getTotalWritten());
threadStats_.addEffectiveBytes(headerBytes, writer.getTotalWritten());
}
});
sendHeartBeat();
// writer.open() deletes files if status == TO_BE_DELETED
// therefore if !(!delete_extra_files && status == TO_BE_DELETED)
// we should skip writer.open() call altogether
if (options_.delete_extra_files ||
blockDetails.allocationStatus != TO_BE_DELETED) {
if (writer.open() != OK) {
threadStats_.setLocalErrorCode(FILE_WRITE_ERROR);
return SEND_ABORT_CMD;
}
}
int32_t checksum = 0;
int64_t remainingData = numRead_ + oldOffset_ - off_;
int64_t toWrite = remainingData;
WDT_CHECK(remainingData >= 0);
if (remainingData >= blockDetails.dataSize) {
toWrite = blockDetails.dataSize;
}
threadStats_.addDataBytes(toWrite);
if (footerType_ == CHECKSUM_FOOTER) {
checksum = folly::crc32c((const uint8_t *)(buf_ + off_), toWrite, checksum);
}
auto throttler = wdtParent_->getThrottler();
if (throttler) {
// We might be reading more than we require for this file but
// throttling should make sense for any additional bytes received
// on the network
throttler->limit(*threadCtx_, toWrite + headerBytes);
}
sendHeartBeat();
ErrorCode code = ERROR;
if (toWrite > 0) {
code = writer.write(buf_ + off_, toWrite);
if (code != OK) {
threadStats_.setLocalErrorCode(code);
return SEND_ABORT_CMD;
}
}
off_ += toWrite;
remainingData -= toWrite;
// also means no leftOver so it's ok we use buf_ from start
while (writer.getTotalWritten() < blockDetails.dataSize) {
if (wdtParent_->getCurAbortCode() != OK) {
WTLOG(ERROR) << "Thread marked for abort while processing "
<< blockDetails.fileName << " " << blockDetails.seqId
<< " port : " << socket_->getPort();
threadStats_.setLocalErrorCode(ABORT);
return FINISH_WITH_ERROR;
}
sendHeartBeat();
int64_t nres = readAtMost(*socket_, buf_, bufSize_,
blockDetails.dataSize - writer.getTotalWritten());
if (nres <= 0) {
break;
}
if (throttler) {
// We only know how much we have read after we are done calling
// readAtMost. Call throttler with the bytes read off_ the wire.
throttler->limit(*threadCtx_, nres);
}
threadStats_.addDataBytes(nres);
if (footerType_ == CHECKSUM_FOOTER) {
checksum = folly::crc32c((const uint8_t *)buf_, nres, checksum);
}
sendHeartBeat();
code = writer.write(buf_, nres);
if (code != OK) {
WTLOG(ERROR) << "failed to write to " << blockDetails.fileName;
threadStats_.setLocalErrorCode(code);
return SEND_ABORT_CMD;
}
}
// Sync the writer to disk and close it. We need to check for error code each
// time, otherwise we would move forward with corrupted files.
const ErrorCode syncCode = writer.sync();
if (syncCode != OK) {
WTLOG(ERROR) << "could not sync " << blockDetails.fileName << " to disk";
threadStats_.setLocalErrorCode(syncCode);
return SEND_ABORT_CMD;
}
const ErrorCode closeCode = writer.close();
if (closeCode != OK) {
WTLOG(ERROR) << "could not close " << blockDetails.fileName;
threadStats_.setLocalErrorCode(closeCode);
return SEND_ABORT_CMD;
}
if (writer.getTotalWritten() != blockDetails.dataSize) {
// This can only happen if there are transmission errors
// Write errors to disk are already taken care of above
WTLOG(ERROR) << "could not read entire content for "
<< blockDetails.fileName << " port " << socket_->getPort();
threadStats_.setLocalErrorCode(SOCKET_READ_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
writtenGuard.dismiss();
WVLOG(2) << "completed " << blockDetails.fileName << " off: " << off_
<< " numRead: " << numRead_;
// Transfer of the file is complete here, mark the bytes effective
WDT_CHECK(remainingData >= 0) << "Negative remainingData " << remainingData;
if (remainingData > 0) {
// if we need to read more anyway, let's move the data
numRead_ = remainingData;
if ((remainingData < Protocol::kMaxHeader) && (off_ > (bufSize_ / 2))) {
// rare so inefficient is ok
WVLOG(3) << "copying extra " << remainingData << " leftover bytes @ "
<< off_;
memmove(/* dst */ buf_,
/* from */ buf_ + off_,
/* how much */ remainingData);
off_ = 0;
} else {
// otherwise just continue from the offset
WVLOG(3) << "Using remaining extra " << remainingData
<< " leftover bytes starting @ " << off_;
}
} else {
numRead_ = off_ = 0;
}
if (footerType_ == CHECKSUM_FOOTER) {
sendHeartBeat();
// have to read footer cmd
oldOffset_ = off_;
numRead_ = readAtLeast(*socket_, buf_ + off_, bufSize_ - off_,
Protocol::kMinBufLength, numRead_);
if (numRead_ < Protocol::kMinBufLength) {
WTLOG(ERROR) << "socket read failure " << Protocol::kMinBufLength << " "
<< numRead_;
threadStats_.setLocalErrorCode(SOCKET_READ_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
Protocol::CMD_MAGIC cmd = (Protocol::CMD_MAGIC)buf_[off_++];
if (cmd != Protocol::FOOTER_CMD) {
WTLOG(ERROR) << "Expecting footer cmd, but received " << cmd;
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
int32_t receivedChecksum;
bool ok = Protocol::decodeFooter(
buf_, off_, oldOffset_ + Protocol::kMaxFooter, receivedChecksum);
if (!ok) {
WTLOG(ERROR) << "Unable to decode footer cmd";
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
if (checksum != receivedChecksum) {
WTLOG(ERROR) << "Checksum mismatch " << checksum << " "
<< receivedChecksum << " port " << socket_->getPort()
<< " file " << blockDetails.fileName;
threadStats_.setLocalErrorCode(CHECKSUM_MISMATCH);
return ACCEPT_WITH_TIMEOUT;
}
markBlockVerified(blockDetails);
int64_t msgLen = off_ - oldOffset_;
numRead_ -= msgLen;
} else {
WDT_CHECK(footerType_ == NO_FOOTER);
if (encryptionTypeToTagLen(encryptionType)) {
blocksWaitingVerification_.emplace_back(blockDetails);
} else {
markBlockVerified(blockDetails);
}
}
return READ_NEXT_CMD;
}
void ReceiverThread::markBlockVerified(const BlockDetails &blockDetails) {
threadStats_.addEffectiveBytes(0, blockDetails.dataSize);
threadStats_.incrNumBlocks();
checkpoint_.incrNumBlocks();
if (!options_.isLogBasedResumption()) {
return;
}
TransferLogManager &transferLogManager = wdtParent_->getTransferLogManager();
if (blockDetails.allocationStatus == TO_BE_DELETED) {
transferLogManager.addFileInvalidationEntry(blockDetails.seqId);
return;
}
transferLogManager.addBlockWriteEntry(blockDetails.seqId, blockDetails.offset,
blockDetails.dataSize);
}
void ReceiverThread::markReceivedBlocksVerified() {
for (const BlockDetails &blockDetails : blocksWaitingVerification_) {
markBlockVerified(blockDetails);
}
blocksWaitingVerification_.clear();
}
ReceiverState ReceiverThread::processDoneCmd() {
WTVLOG(1) << "entered PROCESS_DONE_CMD state";
if (numRead_ != Protocol::kMinBufLength) {
WTLOG(ERROR) << "Unexpected state for done command"
<< " off_: " << off_ << " numRead_: " << numRead_;
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
ErrorCode senderStatus = (ErrorCode)buf_[off_++];
int64_t numBlocksSend = -1;
int64_t totalSenderBytes = -1;
bool success = Protocol::decodeDone(threadProtocolVersion_, buf_, off_,
oldOffset_ + Protocol::kMaxDone,
numBlocksSend, totalSenderBytes);
if (!success) {
WTLOG(ERROR) << "Unable to decode done cmd";
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
threadStats_.setNumBlocksSend(numBlocksSend);
threadStats_.setTotalSenderBytes(totalSenderBytes);
threadStats_.setRemoteErrorCode(senderStatus);
// received a valid command, applying pending checkpoint write update
checkpointIndex_ = pendingCheckpointIndex_;
return WAIT_FOR_FINISH_OR_NEW_CHECKPOINT;
}
ReceiverState ReceiverThread::processSizeCmd() {
WTVLOG(1) << "entered PROCESS_SIZE_CMD state";
int64_t totalSenderBytes;
bool success = Protocol::decodeSize(
buf_, off_, oldOffset_ + Protocol::kMaxSize, totalSenderBytes);
if (!success) {
WTLOG(ERROR) << "Unable to decode size cmd";
threadStats_.setLocalErrorCode(PROTOCOL_ERROR);
return FINISH_WITH_ERROR;
}
WVLOG(1) << "Number of bytes to receive " << totalSenderBytes;
threadStats_.setTotalSenderBytes(totalSenderBytes);
auto msgLen = off_ - oldOffset_;
numRead_ -= msgLen;
return READ_NEXT_CMD;
}
ReceiverState ReceiverThread::sendFileChunks() {
WTLOG(INFO) << "entered SEND_FILE_CHUNKS state";
WDT_CHECK(senderReadTimeout_ > 0); // must have received settings
int waitingTimeMillis = senderReadTimeout_ / kWaitTimeoutFactor;
auto execFunnel = controller_->getFunnel(SEND_FILE_CHUNKS_FUNNEL);
while (true) {
auto status = execFunnel->getStatus();
switch (status) {
case FUNNEL_END: {
buf_[0] = Protocol::ACK_CMD;
int toWrite = 1;
int written = socket_->write(buf_, toWrite);
if (written != toWrite) {
WTLOG(ERROR) << "socket write error " << toWrite << " " << written;
threadStats_.setLocalErrorCode(SOCKET_WRITE_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
threadStats_.addHeaderBytes(toWrite);
return READ_NEXT_CMD;
}
case FUNNEL_PROGRESS: {
buf_[0] = Protocol::WAIT_CMD;
int toWrite = 1;
int written = socket_->write(buf_, toWrite);
if (written != toWrite) {
WTLOG(ERROR) << "socket write error " << toWrite << " " << written;
threadStats_.setLocalErrorCode(SOCKET_WRITE_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
threadStats_.addHeaderBytes(toWrite);
execFunnel->wait(waitingTimeMillis, *threadCtx_);
break;
}
case FUNNEL_START: {
int64_t off = 0;
buf_[off++] = Protocol::CHUNKS_CMD;
const auto &fileChunksInfo = wdtParent_->getFileChunksInfo();
const int64_t numParsedChunksInfo = fileChunksInfo.size();
Protocol::encodeChunksCmd(buf_, off, /* size of buf_ */ bufSize_,
/* param to send */ bufSize_,
numParsedChunksInfo);
int written = socket_->write(buf_, off);
if (written > 0) {
threadStats_.addHeaderBytes(written);
}
if (written != off) {
WTLOG(ERROR) << "socket write err " << off << " " << written;
threadStats_.setLocalErrorCode(SOCKET_READ_ERROR);
execFunnel->notifyFail();
return ACCEPT_WITH_TIMEOUT;
}
int64_t numEntriesWritten = 0;
// we try to encode as many chunks as possible in the buffer. If a
// single
// chunk can not fit in the buffer, it is ignored. Format of encoding :
// <data-size><chunk1><chunk2>...
while (numEntriesWritten < numParsedChunksInfo) {
off = sizeof(int32_t);
int64_t numEntriesEncoded = Protocol::encodeFileChunksInfoList(
buf_, off, bufSize_, numEntriesWritten, fileChunksInfo);
int32_t dataSize = folly::Endian::little(off - sizeof(int32_t));
folly::storeUnaligned<int32_t>(buf_, dataSize);
written = socket_->write(buf_, off);
if (written > 0) {
threadStats_.addHeaderBytes(written);
}
if (written != off) {
break;
}
numEntriesWritten += numEntriesEncoded;
}
if (numEntriesWritten != numParsedChunksInfo) {
WTLOG(ERROR) << "Could not write all the file chunks "
<< numParsedChunksInfo << " " << numEntriesWritten;
threadStats_.setLocalErrorCode(SOCKET_WRITE_ERROR);
execFunnel->notifyFail();
return ACCEPT_WITH_TIMEOUT;
}
// try to read ack
int64_t toRead = 1;
int64_t numRead = socket_->read(buf_, toRead);
if (numRead != toRead) {
WTLOG(ERROR) << "Socket read error " << toRead << " " << numRead;
threadStats_.setLocalErrorCode(SOCKET_READ_ERROR);
execFunnel->notifyFail();
return ACCEPT_WITH_TIMEOUT;
}
wdtParent_->addTransferLogHeader(isBlockMode_,
/* sender resuming */ true);
execFunnel->notifySuccess();
return READ_NEXT_CMD;
}
}
}
}
ReceiverState ReceiverThread::sendGlobalCheckpoint() {
WTLOG(INFO) << "entered SEND_GLOBAL_CHECKPOINTS state";
buf_[0] = Protocol::ERR_CMD;
off_ = 1;
// leave space for length
off_ += sizeof(int16_t);
auto oldOffset = off_;
Protocol::encodeCheckpoints(threadProtocolVersion_, buf_, off_, bufSize_,
newCheckpoints_);
int16_t length = off_ - oldOffset;
folly::storeUnaligned<int16_t>(buf_ + 1, folly::Endian::little(length));
int written = socket_->write(buf_, off_);
if (written != off_) {
WTLOG(ERROR) << "unable to write error checkpoints";
threadStats_.setLocalErrorCode(SOCKET_WRITE_ERROR);
return ACCEPT_WITH_TIMEOUT;
} else {
threadStats_.addHeaderBytes(off_);
pendingCheckpointIndex_ = checkpointIndex_ + newCheckpoints_.size();
numRead_ = off_ = 0;
return READ_NEXT_CMD;
}
}
ReceiverState ReceiverThread::sendAbortCmd() {
WTLOG(INFO) << "entered SEND_ABORT_CMD state";
int64_t offset = 0;
buf_[offset++] = Protocol::ABORT_CMD;
Protocol::encodeAbort(buf_, offset, bufSize_, threadProtocolVersion_,
threadStats_.getLocalErrorCode(),
threadStats_.getNumFiles());
socket_->write(buf_, offset);
// No need to check if we were successful in sending ABORT
// This thread will simply disconnect and sender thread on the
// other side will timeout
socket_->closeConnection();
threadStats_.addHeaderBytes(offset);
if (threadStats_.getLocalErrorCode() == VERSION_MISMATCH) {
// Receiver should try again expecting sender to have changed its version
return ACCEPT_WITH_TIMEOUT;
}
return FINISH_WITH_ERROR;
}
ReceiverState ReceiverThread::sendDoneCmd() {
WTVLOG(1) << "entered SEND_DONE_CMD state";
buf_[0] = Protocol::DONE_CMD;
if (socket_->write(buf_, 1) != 1) {
WTPLOG(ERROR) << "unable to send DONE " << threadIndex_;
threadStats_.setLocalErrorCode(SOCKET_WRITE_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
threadStats_.addHeaderBytes(1);
auto read = socket_->read(buf_, 1);
if (read != 1 || buf_[0] != Protocol::DONE_CMD) {
WTLOG(ERROR) << "did not receive ack for DONE";
threadStats_.setLocalErrorCode(SOCKET_READ_ERROR);
return ACCEPT_WITH_TIMEOUT;
}
ErrorCode code = socket_->expectEndOfStream();
if (code != OK) {
WTLOG(ERROR) << "error while processing logical end of stream "
<< errorCodeToStr(code);
threadStats_.setLocalErrorCode(code);
return ACCEPT_WITH_TIMEOUT;
}
markReceivedBlocksVerified();
threadStats_.setLocalErrorCode(socket_->closeConnection());
WTLOG(INFO) << "got ack for DONE and logical eof. Transfer finished";
return END;
}
ReceiverState ReceiverThread::finishWithError() {
WTLOG(INFO) << "entered FINISH_WITH_ERROR state";
// should only be in this state if there is some error
WDT_CHECK(threadStats_.getLocalErrorCode() != OK);
// close the socket, so that sender receives an error during connect
// When we are doing a single session, close the listening socket as soon
// as we are done
if (wdtParent_->isJoinable_) {
socket_->closeAllNoCheck();
} else {
socket_->closeNoCheck();
}
auto cv = controller_->getCondition(WAIT_FOR_FINISH_OR_CHECKPOINT_CV);
auto guard = cv->acquire();
wdtParent_->addCheckpoint(checkpoint_);
controller_->markState(threadIndex_, FINISHED);
guard.notifyOne();
return END;
}
ReceiverState ReceiverThread::checkForFinishOrNewCheckpoints() {
auto checkpoints = wdtParent_->getNewCheckpoints(checkpointIndex_);
if (!checkpoints.empty()) {
newCheckpoints_ = std::move(checkpoints);
controller_->markState(threadIndex_, RUNNING);
return SEND_GLOBAL_CHECKPOINTS;
}
bool existActiveThreads = controller_->hasThreads(threadIndex_, RUNNING);
if (!existActiveThreads) {
controller_->markState(threadIndex_, FINISHED);
return SEND_DONE_CMD;
}
return WAIT_FOR_FINISH_OR_NEW_CHECKPOINT;
}
ReceiverState ReceiverThread::waitForFinishOrNewCheckpoint() {
WTLOG(INFO) << "entered WAIT_FOR_FINISH_OR_NEW_CHECKPOINT state";
// should only be called if the are no errors
WDT_CHECK(threadStats_.getLocalErrorCode() == OK);
auto cv = controller_->getCondition(WAIT_FOR_FINISH_OR_CHECKPOINT_CV);
int timeoutMillis = senderReadTimeout_ / kWaitTimeoutFactor;
controller_->markState(threadIndex_, WAITING);
while (true) {
WDT_CHECK(senderReadTimeout_ > 0); // must have received settings
{
auto guard = cv->acquire();
auto state = checkForFinishOrNewCheckpoints();
if (state != WAIT_FOR_FINISH_OR_NEW_CHECKPOINT) {
guard.notifyOne();
return state;
}
{
PerfStatCollector statCollector(*threadCtx_,
PerfStatReport::RECEIVER_WAIT_SLEEP);
guard.wait(timeoutMillis, *threadCtx_);
}
state = checkForFinishOrNewCheckpoints();
if (state != WAIT_FOR_FINISH_OR_NEW_CHECKPOINT) {
guard.notifyOne();
return state;
}
}
// send WAIT cmd to keep sender thread alive
buf_[0] = Protocol::WAIT_CMD;
if (socket_->write(buf_, 1) != 1) {
WTPLOG(ERROR) << "unable to write WAIT";
threadStats_.setLocalErrorCode(SOCKET_WRITE_ERROR);
controller_->markState(threadIndex_, RUNNING);
return ACCEPT_WITH_TIMEOUT;
}
threadStats_.addHeaderBytes(1);
}
}
void ReceiverThread::start() {
if (buf_ == nullptr) {
WTLOG(ERROR) << "Unable to allocate buffer";
threadStats_.setLocalErrorCode(MEMORY_ALLOCATION_ERROR);
return;
}
ReceiverState state = LISTEN;
while (true) {
ErrorCode abortCode = wdtParent_->getCurAbortCode();
if (abortCode != OK) {
WTLOG(ERROR) << "Transfer aborted " << socket_->getPort() << " "
<< errorCodeToStr(abortCode);
threadStats_.setLocalErrorCode(ABORT);
break;
}
if (state == END) {
break;