-
Notifications
You must be signed in to change notification settings - Fork 389
/
Sender.cpp
1456 lines (1360 loc) · 51.4 KB
/
Sender.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. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "Sender.h"
#include "ClientSocket.h"
#include "Throttler.h"
#include "SocketUtils.h"
#include <folly/Conv.h>
#include <folly/Memory.h>
#include <folly/String.h>
#include <folly/Bits.h>
#include <folly/ScopeGuard.h>
#include <sys/stat.h>
#include <folly/Checksum.h>
#include <thread>
namespace facebook {
namespace wdt {
ThreadTransferHistory::ThreadTransferHistory(DirectorySourceQueue &queue,
TransferStats &threadStats)
: queue_(queue), threadStats_(threadStats) {
}
std::string ThreadTransferHistory::getSourceId(int64_t index) {
folly::SpinLockGuard guard(lock_);
std::string sourceId;
const int64_t historySize = history_.size();
if (index >= 0 && index < historySize) {
sourceId = history_[index]->getIdentifier();
} else {
LOG(WARNING) << "Trying to read out of bounds data " << index << " "
<< history_.size();
}
return sourceId;
}
bool ThreadTransferHistory::addSource(std::unique_ptr<ByteSource> &source) {
folly::SpinLockGuard guard(lock_);
if (globalCheckpoint_) {
// already received an error for this thread
VLOG(1) << "adding source after global checkpoint is received. Returning "
"the source to the queue";
markSourceAsFailed(source, lastCheckpoint_.get());
lastCheckpoint_.reset();
queue_.returnToQueue(source);
return false;
}
history_.emplace_back(std::move(source));
return true;
}
ErrorCode ThreadTransferHistory::setCheckpointAndReturnToQueue(
const Checkpoint &checkpoint, bool globalCheckpoint) {
folly::SpinLockGuard guard(lock_);
const int64_t historySize = history_.size();
int64_t numReceivedSources = checkpoint.numBlocks;
int64_t lastBlockReceivedBytes = checkpoint.lastBlockReceivedBytes;
if (numReceivedSources > historySize) {
LOG(ERROR)
<< "checkpoint is greater than total number of sources transfered "
<< history_.size() << " " << numReceivedSources;
return INVALID_CHECKPOINT;
}
ErrorCode errCode = validateCheckpoint(checkpoint, globalCheckpoint);
if (errCode == INVALID_CHECKPOINT) {
return INVALID_CHECKPOINT;
}
globalCheckpoint_ |= globalCheckpoint;
lastCheckpoint_ = folly::make_unique<Checkpoint>(checkpoint);
int64_t numFailedSources = historySize - numReceivedSources;
if (numFailedSources == 0 && lastBlockReceivedBytes > 0) {
if (!globalCheckpoint) {
// no block to apply checkpoint offset. This can happen if we receive same
// local checkpoint without adding anything to the history
LOG(WARNING) << "Local checkpoint has received bytes for last block, but "
"there are no unacked blocks in the history. Ignoring.";
}
}
numAcknowledged_ = numReceivedSources;
std::vector<std::unique_ptr<ByteSource>> sourcesToReturn;
for (int64_t i = 0; i < numFailedSources; i++) {
std::unique_ptr<ByteSource> source = std::move(history_.back());
history_.pop_back();
const Checkpoint *checkpointPtr =
(i == numFailedSources - 1 ? &checkpoint : nullptr);
markSourceAsFailed(source, checkpointPtr);
sourcesToReturn.emplace_back(std::move(source));
}
queue_.returnToQueue(sourcesToReturn);
LOG(INFO) << numFailedSources
<< " number of sources returned to queue, checkpoint: "
<< checkpoint;
return errCode;
}
std::vector<TransferStats> ThreadTransferHistory::popAckedSourceStats() {
const int64_t historySize = history_.size();
WDT_CHECK(numAcknowledged_ == historySize);
// no locking needed, as this should be called after transfer has finished
std::vector<TransferStats> sourceStats;
while (!history_.empty()) {
sourceStats.emplace_back(std::move(history_.back()->getTransferStats()));
history_.pop_back();
}
return sourceStats;
}
void ThreadTransferHistory::markAllAcknowledged() {
folly::SpinLockGuard guard(lock_);
numAcknowledged_ = history_.size();
}
void ThreadTransferHistory::returnUnackedSourcesToQueue() {
Checkpoint checkpoint;
checkpoint.numBlocks = numAcknowledged_;
setCheckpointAndReturnToQueue(checkpoint, false);
}
ErrorCode ThreadTransferHistory::validateCheckpoint(
const Checkpoint &checkpoint, bool globalCheckpoint) {
if (lastCheckpoint_ == nullptr) {
return OK;
}
if (checkpoint.numBlocks < lastCheckpoint_->numBlocks) {
LOG(ERROR) << "Current checkpoint must be higher than previous checkpoint, "
"Last checkpoint: "
<< *lastCheckpoint_ << ", Current checkpoint: " << checkpoint;
return INVALID_CHECKPOINT;
}
if (checkpoint.numBlocks > lastCheckpoint_->numBlocks) {
return OK;
}
bool noProgress = false;
// numBlocks same
if (checkpoint.lastBlockSeqId == lastCheckpoint_->lastBlockSeqId &&
checkpoint.lastBlockOffset == lastCheckpoint_->lastBlockOffset) {
// same block
if (checkpoint.lastBlockReceivedBytes !=
lastCheckpoint_->lastBlockReceivedBytes) {
LOG(ERROR) << "Current checkpoint has different received bytes, but all "
"other fields are same, Last checkpoint "
<< *lastCheckpoint_ << ", Current checkpoint: " << checkpoint;
return INVALID_CHECKPOINT;
}
noProgress = true;
} else {
// different block
WDT_CHECK(checkpoint.lastBlockReceivedBytes >= 0);
if (checkpoint.lastBlockReceivedBytes == 0) {
noProgress = true;
}
}
if (noProgress && !globalCheckpoint) {
// we can get same global checkpoint multiple times, so no need to check for
// progress
LOG(WARNING) << "No progress since last checkpoint, Last checkpoint: "
<< *lastCheckpoint_ << ", Current checkpoint: " << checkpoint;
return NO_PROGRESS;
}
return OK;
}
void ThreadTransferHistory::markSourceAsFailed(
std::unique_ptr<ByteSource> &source, const Checkpoint *checkpoint) {
auto metadata = source->getMetaData();
bool validCheckpoint = false;
if (checkpoint != nullptr) {
if (checkpoint->hasSeqId) {
if ((checkpoint->lastBlockSeqId == metadata.seqId) &&
(checkpoint->lastBlockOffset == source->getOffset())) {
validCheckpoint = true;
} else {
LOG(WARNING)
<< "Checkpoint block does not match history block. Checkpoint: "
<< checkpoint->lastBlockSeqId << ", " << checkpoint->lastBlockOffset
<< " History: " << metadata.seqId << ", " << source->getOffset();
}
} else {
// Receiver at lower version!
// checkpoint does not have seq-id. We have to blindly trust
// lastBlockReceivedBytes. If we do not, transfer will fail because of
// number of bytes mismatch. Even if an error happens because of this,
// Receiver will fail.
validCheckpoint = true;
}
}
int64_t receivedBytes =
(validCheckpoint ? checkpoint->lastBlockReceivedBytes : 0);
TransferStats &sourceStats = source->getTransferStats();
if (sourceStats.getErrorCode() != OK) {
// already marked as failed
sourceStats.addEffectiveBytes(0, receivedBytes);
threadStats_.addEffectiveBytes(0, receivedBytes);
} else {
auto dataBytes = source->getSize();
auto headerBytes = sourceStats.getEffectiveHeaderBytes();
int64_t wastedBytes = dataBytes - receivedBytes;
sourceStats.subtractEffectiveBytes(headerBytes, wastedBytes);
sourceStats.decrNumBlocks();
sourceStats.setErrorCode(SOCKET_WRITE_ERROR);
sourceStats.incrFailedAttempts();
threadStats_.subtractEffectiveBytes(headerBytes, wastedBytes);
threadStats_.decrNumBlocks();
threadStats_.incrFailedAttempts();
}
source->advanceOffset(receivedBytes);
}
const Sender::StateFunction Sender::stateMap_[] = {
&Sender::connect, &Sender::readLocalCheckPoint,
&Sender::sendSettings, &Sender::sendBlocks,
&Sender::sendDoneCmd, &Sender::sendSizeCmd,
&Sender::checkForAbort, &Sender::readFileChunks,
&Sender::readReceiverCmd, &Sender::processDoneCmd,
&Sender::processWaitCmd, &Sender::processErrCmd,
&Sender::processAbortCmd, &Sender::processVersionMismatch};
Sender::Sender(const std::string &destHost, const std::string &srcDir)
: queueAbortChecker_(this) {
LOG(INFO) << "WDT Sender " << Protocol::getFullVersion();
destHost_ = destHost;
srcDir_ = srcDir;
transferFinished_ = true;
const auto &options = WdtOptions::get();
int port = options.start_port;
int numSockets = options.num_ports;
for (int i = 0; i < numSockets; i++) {
ports_.push_back(port + i);
}
dirQueue_.reset(new DirectorySourceQueue(srcDir_, &queueAbortChecker_));
VLOG(3) << "Configuring the directory queue";
dirQueue_->setIncludePattern(options.include_regex);
dirQueue_->setExcludePattern(options.exclude_regex);
dirQueue_->setPruneDirPattern(options.prune_dir_regex);
dirQueue_->setFollowSymlinks(options.follow_symlinks);
dirQueue_->setBlockSizeMbytes(options.block_size_mbytes);
progressReportIntervalMillis_ = options.progress_report_interval_millis;
progressReporter_ = folly::make_unique<ProgressReporter>();
}
Sender::Sender(const WdtTransferRequest &transferRequest)
: Sender(transferRequest.hostName, transferRequest.directory,
transferRequest.ports, transferRequest.fileInfo) {
transferId_ = transferRequest.transferId;
if (transferId_.empty()) {
transferId_ = WdtBase::generateTransferId();
}
setProtocolVersion(transferRequest.protocolVersion);
}
Sender::Sender(const std::string &destHost, const std::string &srcDir,
const std::vector<int32_t> &ports,
const std::vector<FileInfo> &srcFileInfo)
: Sender(destHost, srcDir) {
ports_ = ports;
dirQueue_->setFileInfo(srcFileInfo);
}
WdtTransferRequest Sender::init() {
WdtTransferRequest transferRequest(getPorts());
transferRequest.transferId = transferId_;
transferRequest.protocolVersion = protocolVersion_;
transferRequest.directory = srcDir_;
transferRequest.hostName = destHost_;
// TODO Figure out what to do with file info
// transferRequest.fileInfo = dirQueue_->getFileInfo();
transferRequest.errorCode = OK;
return transferRequest;
}
Sender::~Sender() {
if (!isTransferFinished()) {
LOG(WARNING) << "Sender being deleted. Forcefully aborting the transfer";
abort(ABORTED_BY_APPLICATION);
}
finish();
}
void Sender::setIncludeRegex(const std::string &includeRegex) {
dirQueue_->setIncludePattern(includeRegex);
}
void Sender::setExcludeRegex(const std::string &excludeRegex) {
dirQueue_->setExcludePattern(excludeRegex);
}
void Sender::setPruneDirRegex(const std::string &pruneDirRegex) {
dirQueue_->setPruneDirPattern(pruneDirRegex);
}
void Sender::setSrcFileInfo(const std::vector<FileInfo> &srcFileInfo) {
dirQueue_->setFileInfo(srcFileInfo);
}
void Sender::setFollowSymlinks(const bool followSymlinks) {
dirQueue_->setFollowSymlinks(followSymlinks);
}
void Sender::setProgressReportIntervalMillis(
const int progressReportIntervalMillis) {
progressReportIntervalMillis_ = progressReportIntervalMillis;
}
const std::vector<int32_t> &Sender::getPorts() const {
return ports_;
}
const std::string &Sender::getSrcDir() const {
return srcDir_;
}
const std::string &Sender::getDestination() const {
return destHost_;
}
std::unique_ptr<TransferReport> Sender::getTransferReport() {
int64_t totalFileSize = dirQueue_->getTotalSize();
double totalTime = durationSeconds(Clock::now() - startTime_);
std::unique_ptr<TransferReport> transferReport =
folly::make_unique<TransferReport>(globalThreadStats_, totalTime,
totalFileSize);
return transferReport;
}
bool Sender::isTransferFinished() {
std::unique_lock<std::mutex> lock(mutex_);
return transferFinished_;
}
Clock::time_point Sender::getEndTime() {
return endTime_;
}
std::unique_ptr<TransferReport> Sender::finish() {
std::unique_lock<std::mutex> instanceLock(instanceManagementMutex_);
VLOG(1) << "Sender::finish()";
if (areThreadsJoined_) {
VLOG(1) << "Threads have already been joined. Returning the"
<< " existing transfer report";
return getTransferReport();
}
const auto &options = WdtOptions::get();
const bool twoPhases = options.two_phases;
bool progressReportEnabled =
progressReporter_ && progressReportIntervalMillis_ > 0;
const int64_t numPorts = ports_.size();
for (int64_t i = 0; i < numPorts; i++) {
senderThreads_[i].join();
}
if (!twoPhases) {
dirThread_.join();
}
WDT_CHECK(numActiveThreads_ == 0);
if (progressReportEnabled) {
{
std::unique_lock<std::mutex> lock(mutex_);
conditionFinished_.notify_all();
}
progressReporterThread_.join();
}
bool allSourcesAcked = false;
for (auto &stats : globalThreadStats_) {
if (stats.getErrorCode() == OK) {
// at least one thread finished correctly
// that means all transferred sources are acked
allSourcesAcked = true;
break;
}
}
std::vector<TransferStats> transferredSourceStats;
for (auto &transferHistory : transferHistories_) {
if (allSourcesAcked) {
transferHistory.markAllAcknowledged();
} else {
transferHistory.returnUnackedSourcesToQueue();
}
if (WdtOptions::get().full_reporting) {
std::vector<TransferStats> stats = transferHistory.popAckedSourceStats();
transferredSourceStats.insert(transferredSourceStats.end(),
std::make_move_iterator(stats.begin()),
std::make_move_iterator(stats.end()));
}
}
if (WdtOptions::get().full_reporting) {
validateTransferStats(transferredSourceStats,
dirQueue_->getFailedSourceStats(),
globalThreadStats_);
}
int64_t totalFileSize = dirQueue_->getTotalSize();
double totalTime = durationSeconds(endTime_ - startTime_);
std::unique_ptr<TransferReport> transferReport =
folly::make_unique<TransferReport>(
transferredSourceStats, dirQueue_->getFailedSourceStats(),
globalThreadStats_, dirQueue_->getFailedDirectories(), totalTime,
totalFileSize, dirQueue_->getCount());
if (progressReportEnabled) {
progressReporter_->end(transferReport);
}
if (options.enable_perf_stat_collection) {
PerfStatReport report;
for (auto &perfReport : perfReports_) {
report += perfReport;
}
LOG(INFO) << report;
}
double directoryTime;
directoryTime = dirQueue_->getDirectoryTime();
LOG(INFO) << "Total sender time = " << totalTime << " seconds ("
<< directoryTime << " dirTime)"
<< ". Transfer summary : " << *transferReport
<< "\nTotal sender throughput = "
<< transferReport->getThroughputMBps() << " Mbytes/sec ("
<< transferReport->getSummary().getEffectiveTotalBytes() /
(totalTime - directoryTime) / kMbToB
<< " Mbytes/sec pure transfer rate)";
areThreadsJoined_ = true;
return transferReport;
}
ErrorCode Sender::transferAsync() {
return start();
}
std::unique_ptr<TransferReport> Sender::transfer() {
start();
return finish();
}
ErrorCode Sender::start() {
areThreadsJoined_ = false;
transferFinished_ = false;
const auto &options = WdtOptions::get();
const bool twoPhases = options.two_phases;
WDT_CHECK(!(twoPhases && options.enable_download_resumption))
<< "Two phase is not supported with download resumption";
LOG(INFO) << "Client (sending) to " << destHost_ << ", Using ports [ "
<< ports_ << "]";
startTime_ = Clock::now();
downloadResumptionEnabled_ = options.enable_download_resumption;
dirThread_ = std::move(dirQueue_->buildQueueAsynchronously());
if (twoPhases) {
dirThread_.join();
}
bool progressReportEnabled =
progressReporter_ && progressReportIntervalMillis_ > 0;
if (throttler_) {
LOG(INFO) << "Skipping throttler setup. External throttler set."
<< "Throttler details : " << *throttler_;
} else {
configureThrottler();
}
// WARNING: Do not MERGE the following two loops. ThreadTransferHistory keeps
// a reference of TransferStats. And, any emplace operation on a vector
// invalidates all its references
const int64_t numPorts = ports_.size();
for (int64_t i = 0; i < numPorts; i++) {
globalThreadStats_.emplace_back(true);
}
for (int64_t i = 0; i < numPorts; i++) {
transferHistories_.emplace_back(*dirQueue_, globalThreadStats_[i]);
}
perfReports_.resize(numPorts);
negotiatedProtocolVersions_.resize(numPorts, 0);
numActiveThreads_ = numPorts;
for (int64_t i = 0; i < numPorts; i++) {
globalThreadStats_[i].setId(folly::to<std::string>(i));
senderThreads_.emplace_back(&Sender::sendOne, this, i);
}
if (progressReportEnabled) {
progressReporter_->start();
std::thread reporterThread(&Sender::reportProgress, this);
progressReporterThread_ = std::move(reporterThread);
}
return OK;
}
void Sender::validateTransferStats(
const std::vector<TransferStats> &transferredSourceStats,
const std::vector<TransferStats> &failedSourceStats,
const std::vector<TransferStats> &threadStats) {
int64_t sourceFailedAttempts = 0;
int64_t sourceDataBytes = 0;
int64_t sourceEffectiveDataBytes = 0;
int64_t sourceNumBlocks = 0;
int64_t threadFailedAttempts = 0;
int64_t threadDataBytes = 0;
int64_t threadEffectiveDataBytes = 0;
int64_t threadNumBlocks = 0;
for (const auto &stat : transferredSourceStats) {
sourceFailedAttempts += stat.getFailedAttempts();
sourceDataBytes += stat.getDataBytes();
sourceEffectiveDataBytes += stat.getEffectiveDataBytes();
sourceNumBlocks += stat.getNumBlocks();
}
for (const auto &stat : failedSourceStats) {
sourceFailedAttempts += stat.getFailedAttempts();
sourceDataBytes += stat.getDataBytes();
sourceEffectiveDataBytes += stat.getEffectiveDataBytes();
sourceNumBlocks += stat.getNumBlocks();
}
for (const auto &stat : threadStats) {
threadFailedAttempts += stat.getFailedAttempts();
threadDataBytes += stat.getDataBytes();
threadEffectiveDataBytes += stat.getEffectiveDataBytes();
threadNumBlocks += stat.getNumBlocks();
}
WDT_CHECK(sourceFailedAttempts == threadFailedAttempts);
WDT_CHECK(sourceDataBytes == threadDataBytes);
WDT_CHECK(sourceEffectiveDataBytes == threadEffectiveDataBytes);
WDT_CHECK(sourceNumBlocks == threadNumBlocks);
}
void Sender::setSocketCreator(const SocketCreator socketCreator) {
socketCreator_ = socketCreator;
}
std::unique_ptr<ClientSocket> Sender::connectToReceiver(const int port,
ErrorCode &errCode) {
auto startTime = Clock::now();
const auto &options = WdtOptions::get();
int connectAttempts = 0;
std::unique_ptr<ClientSocket> socket;
if (!socketCreator_) {
// socket creator not set, creating ClientSocket
socket = folly::make_unique<ClientSocket>(
destHost_, folly::to<std::string>(port), &abortCheckerCallback_);
} else {
socket = socketCreator_(destHost_, folly::to<std::string>(port),
&abortCheckerCallback_);
}
double retryInterval = options.sleep_millis;
int maxRetries = options.max_retries;
if (maxRetries < 1) {
LOG(ERROR) << "Invalid max_retries " << maxRetries << " using 1 instead";
maxRetries = 1;
}
for (int i = 1; i <= maxRetries; ++i) {
++connectAttempts;
errCode = socket->connect();
if (errCode == OK) {
break;
} else if (errCode == CONN_ERROR) {
return nullptr;
}
if (getCurAbortCode() != OK) {
errCode = ABORT;
return nullptr;
}
if (i != maxRetries) {
// sleep between attempts but not after the last
VLOG(1) << "Sleeping after failed attempt " << i;
usleep(retryInterval * 1000);
}
}
double elapsedSecsConn = durationSeconds(Clock::now() - startTime);
if (errCode != OK) {
LOG(ERROR) << "Unable to connect to " << destHost_ << " " << port
<< " despite " << connectAttempts << " retries in "
<< elapsedSecsConn << " seconds.";
errCode = CONN_ERROR;
return nullptr;
}
((connectAttempts > 1) ? LOG(WARNING) : LOG(INFO))
<< "Connection took " << connectAttempts << " attempt(s) and "
<< elapsedSecsConn << " seconds. port " << port;
return socket;
}
Sender::SenderState Sender::connect(ThreadData &data) {
VLOG(1) << "entered CONNECT state " << data.threadIndex_;
int port = ports_[data.threadIndex_];
TransferStats &threadStats = data.threadStats_;
auto &socket = data.socket_;
auto &numReconnectWithoutProgress = data.numReconnectWithoutProgress_;
auto &options = WdtOptions::get();
if (socket) {
socket->close();
}
if (numReconnectWithoutProgress >= options.max_transfer_retries) {
LOG(ERROR) << "Sender thread reconnected " << numReconnectWithoutProgress
<< " times without making any progress, giving up. port: "
<< socket->getPort();
threadStats.setErrorCode(NO_PROGRESS);
return END;
}
ErrorCode code;
socket = connectToReceiver(port, code);
if (code == ABORT) {
threadStats.setErrorCode(ABORT);
if (getCurAbortCode() == VERSION_MISMATCH) {
return PROCESS_VERSION_MISMATCH;
}
return END;
}
if (code != OK) {
threadStats.setErrorCode(code);
return END;
}
// clearing the totalSizeSent_ flag. This way if anything breaks, we resend
// the total size.
data.totalSizeSent_ = false;
auto nextState =
threadStats.getErrorCode() == OK ? SEND_SETTINGS : READ_LOCAL_CHECKPOINT;
// clear the error code, as this is a new transfer
threadStats.setErrorCode(OK);
return nextState;
}
Sender::SenderState Sender::readLocalCheckPoint(ThreadData &data) {
LOG(INFO) << "entered READ_LOCAL_CHECKPOINT state " << data.threadIndex_;
int port = ports_[data.threadIndex_];
TransferStats &threadStats = data.threadStats_;
ThreadTransferHistory &transferHistory = data.getTransferHistory();
auto &numReconnectWithoutProgress = data.numReconnectWithoutProgress_;
std::vector<Checkpoint> checkpoints;
int64_t decodeOffset = 0;
char *buf = data.buf_;
int checkpointLen = Protocol::getMaxLocalCheckpointLength(protocolVersion_);
int64_t numRead = data.socket_->read(buf, checkpointLen);
if (numRead != checkpointLen) {
LOG(ERROR) << "read mismatch during reading local checkpoint "
<< checkpointLen << " " << numRead << " port " << port;
threadStats.setErrorCode(SOCKET_READ_ERROR);
numReconnectWithoutProgress++;
return CONNECT;
}
if (!Protocol::decodeCheckpoints(protocolVersion_, buf, decodeOffset,
checkpointLen, checkpoints)) {
LOG(ERROR) << "checkpoint decode failure "
<< folly::humanify(std::string(buf, checkpointLen));
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
if (checkpoints.size() != 1 || checkpoints[0].port != port) {
LOG(ERROR) << "illegal local checkpoint "
<< folly::humanify(std::string(buf, checkpointLen));
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
const Checkpoint &checkpoint = checkpoints[0];
auto numBlocks = checkpoint.numBlocks;
VLOG(1) << "received local checkpoint, port " << port << " num-blocks "
<< numBlocks << " seq-id " << checkpoint.lastBlockSeqId << " offset "
<< checkpoint.lastBlockOffset << " received-bytes "
<< checkpoint.lastBlockReceivedBytes;
if (numBlocks == -1) {
// Receiver failed while sending DONE cmd
return READ_RECEIVER_CMD;
}
ErrorCode errCode =
transferHistory.setCheckpointAndReturnToQueue(checkpoint, false);
if (errCode == INVALID_CHECKPOINT) {
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
if (errCode == NO_PROGRESS) {
numReconnectWithoutProgress++;
} else {
numReconnectWithoutProgress = 0;
}
return SEND_SETTINGS;
}
Sender::SenderState Sender::sendSettings(ThreadData &data) {
VLOG(1) << "entered SEND_SETTINGS state " << data.threadIndex_;
TransferStats &threadStats = data.threadStats_;
char *buf = data.buf_;
auto &socket = data.socket_;
auto &options = WdtOptions::get();
int64_t readTimeoutMillis = options.read_timeout_millis;
int64_t writeTimeoutMillis = options.write_timeout_millis;
int64_t off = 0;
buf[off++] = Protocol::SETTINGS_CMD;
bool sendFileChunks;
{
std::lock_guard<std::mutex> lock(mutex_);
sendFileChunks =
(downloadResumptionEnabled_ &&
protocolVersion_ >= Protocol::DOWNLOAD_RESUMPTION_VERSION);
}
Settings settings;
settings.readTimeoutMillis = readTimeoutMillis;
settings.writeTimeoutMillis = writeTimeoutMillis;
settings.transferId = transferId_;
settings.enableChecksum = options.enable_checksum;
settings.sendFileChunks = sendFileChunks;
settings.blockModeDisabled = (options.block_size_mbytes <= 0);
Protocol::encodeSettings(protocolVersion_, buf, off, Protocol::kMaxSettings,
settings);
int64_t toWrite = sendFileChunks ? Protocol::kMinBufLength : off;
int64_t written = socket->write(buf, toWrite);
if (written != toWrite) {
LOG(ERROR) << "Socket write failure " << written << " " << toWrite;
threadStats.setErrorCode(SOCKET_WRITE_ERROR);
return CONNECT;
}
threadStats.addHeaderBytes(toWrite);
return sendFileChunks ? READ_FILE_CHUNKS : SEND_BLOCKS;
}
Sender::SenderState Sender::sendBlocks(ThreadData &data) {
VLOG(1) << "entered SEND_BLOCKS state " << data.threadIndex_;
TransferStats &threadStats = data.threadStats_;
ThreadTransferHistory &transferHistory = data.getTransferHistory();
auto &totalSizeSent = data.totalSizeSent_;
if (protocolVersion_ >= Protocol::RECEIVER_PROGRESS_REPORT_VERSION &&
!totalSizeSent && dirQueue_->fileDiscoveryFinished()) {
return SEND_SIZE_CMD;
}
ErrorCode transferStatus;
std::unique_ptr<ByteSource> source = dirQueue_->getNextSource(transferStatus);
if (!source) {
return SEND_DONE_CMD;
}
WDT_CHECK(!source->hasError());
TransferStats transferStats =
sendOneByteSource(data.socket_, source, transferStatus);
threadStats += transferStats;
source->addTransferStats(transferStats);
source->close();
if (!transferHistory.addSource(source)) {
// global checkpoint received for this thread. no point in
// continuing
LOG(ERROR) << "global checkpoint received, no point in continuing";
threadStats.setErrorCode(CONN_ERROR);
return END;
}
if (transferStats.getErrorCode() != OK) {
return CHECK_FOR_ABORT;
}
return SEND_BLOCKS;
}
Sender::SenderState Sender::sendSizeCmd(ThreadData &data) {
VLOG(1) << "entered SEND_SIZE_CMD state " << data.threadIndex_;
TransferStats &threadStats = data.threadStats_;
char *buf = data.buf_;
auto &socket = data.socket_;
auto &totalSizeSent = data.totalSizeSent_;
int64_t off = 0;
buf[off++] = Protocol::SIZE_CMD;
Protocol::encodeSize(buf, off, Protocol::kMaxSize, dirQueue_->getTotalSize());
int64_t written = socket->write(buf, off);
if (written != off) {
LOG(ERROR) << "Socket write error " << off << " " << written;
threadStats.setErrorCode(SOCKET_WRITE_ERROR);
return CHECK_FOR_ABORT;
}
threadStats.addHeaderBytes(off);
totalSizeSent = true;
return SEND_BLOCKS;
}
Sender::SenderState Sender::sendDoneCmd(ThreadData &data) {
VLOG(1) << "entered SEND_DONE_CMD state " << data.threadIndex_;
TransferStats &threadStats = data.threadStats_;
char *buf = data.buf_;
auto &socket = data.socket_;
int64_t off = 0;
buf[off++] = Protocol::DONE_CMD;
auto pair = dirQueue_->getNumBlocksAndStatus();
int64_t numBlocksDiscovered = pair.first;
ErrorCode transferStatus = pair.second;
buf[off++] = transferStatus;
Protocol::encodeDone(protocolVersion_, buf, off, Protocol::kMaxDone,
numBlocksDiscovered, dirQueue_->getTotalSize());
int toWrite = Protocol::kMinBufLength;
int64_t written = socket->write(buf, toWrite);
if (written != toWrite) {
LOG(ERROR) << "Socket write failure " << written << " " << toWrite;
threadStats.setErrorCode(SOCKET_WRITE_ERROR);
return CHECK_FOR_ABORT;
}
threadStats.addHeaderBytes(toWrite);
VLOG(1) << "Wrote done cmd on " << socket->getFd() << " waiting for reply...";
return READ_RECEIVER_CMD;
}
Sender::SenderState Sender::checkForAbort(ThreadData &data) {
LOG(INFO) << "entered CHECK_FOR_ABORT state " << data.threadIndex_;
char *buf = data.buf_;
auto &threadStats = data.threadStats_;
auto &socket = data.socket_;
auto numRead = socket->read(buf, 1);
if (numRead != 1) {
VLOG(1) << "No abort cmd found";
return CONNECT;
}
Protocol::CMD_MAGIC cmd = (Protocol::CMD_MAGIC)buf[0];
if (cmd != Protocol::ABORT_CMD) {
VLOG(1) << "Unexpected result found while reading for abort " << buf[0];
return CONNECT;
}
threadStats.addHeaderBytes(1);
return PROCESS_ABORT_CMD;
}
Sender::SenderState Sender::readFileChunks(ThreadData &data) {
LOG(INFO) << "entered READ_FILE_CHUNKS state " << data.threadIndex_;
char *buf = data.buf_;
auto &socket = data.socket_;
auto &threadStats = data.threadStats_;
int64_t numRead = socket->read(buf, 1);
if (numRead != 1) {
LOG(ERROR) << "Socket read error 1 " << numRead;
threadStats.setErrorCode(SOCKET_READ_ERROR);
return CHECK_FOR_ABORT;
}
threadStats.addHeaderBytes(numRead);
Protocol::CMD_MAGIC cmd = (Protocol::CMD_MAGIC)buf[0];
if (cmd == Protocol::ABORT_CMD) {
return PROCESS_ABORT_CMD;
}
if (cmd == Protocol::WAIT_CMD) {
return READ_FILE_CHUNKS;
}
if (cmd == Protocol::ACK_CMD) {
{
std::lock_guard<std::mutex> lock(mutex_);
if (!fileChunksReceived_) {
LOG(ERROR) << "Sender has not yet received file chunks, but receiver "
"thinks it has already sent it";
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
}
return SEND_BLOCKS;
}
if (cmd != Protocol::CHUNKS_CMD) {
LOG(ERROR) << "Unexpected cmd " << cmd;
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
int64_t toRead = Protocol::kChunksCmdLen;
numRead = socket->read(buf, toRead);
if (numRead != toRead) {
LOG(ERROR) << "Socket read error " << toRead << " " << numRead;
threadStats.setErrorCode(SOCKET_READ_ERROR);
return CHECK_FOR_ABORT;
}
threadStats.addHeaderBytes(numRead);
int64_t off = 0;
int64_t bufSize, numFiles;
Protocol::decodeChunksCmd(buf, off, bufSize, numFiles);
LOG(INFO) << "File chunk list has " << numFiles
<< " entries and is broken in buffers of length " << bufSize;
std::unique_ptr<char[]> chunkBuffer(new char[bufSize]);
std::vector<FileChunksInfo> fileChunksInfoList;
while (true) {
int64_t numFileChunks = fileChunksInfoList.size();
if (numFileChunks > numFiles) {
// We should never be able to read more file chunks than mentioned in the
// chunks cmd. Chunks cmd has buffer size used to transfer chunks and also
// number of chunks. This chunks are read and parsed and added to
// fileChunksInfoList. Number of chunks we decode should match with the
// number mentioned in the Chunks cmd.
LOG(ERROR) << "Number of file chunks received is more than the number "
"mentioned in CHUNKS_CMD "
<< numFileChunks << " " << numFiles;
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
if (numFileChunks == numFiles) {
break;
}
toRead = sizeof(int32_t);
numRead = socket->read(buf, toRead);
if (numRead != toRead) {
LOG(ERROR) << "Socket read error " << toRead << " " << numRead;
threadStats.setErrorCode(SOCKET_READ_ERROR);
return CHECK_FOR_ABORT;
}
toRead = folly::loadUnaligned<int32_t>(buf);
toRead = folly::Endian::little(toRead);
numRead = socket->read(chunkBuffer.get(), toRead);
if (numRead != toRead) {
LOG(ERROR) << "Socket read error " << toRead << " " << numRead;
threadStats.setErrorCode(SOCKET_READ_ERROR);
return CHECK_FOR_ABORT;
}
threadStats.addHeaderBytes(numRead);
off = 0;
// decode function below adds decoded file chunks to fileChunksInfoList
bool success = Protocol::decodeFileChunksInfoList(
chunkBuffer.get(), off, toRead, fileChunksInfoList);
if (!success) {
LOG(ERROR) << "Unable to decode file chunks list";
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
}
{
std::lock_guard<std::mutex> lock(mutex_);
if (fileChunksReceived_) {
LOG(WARNING) << "File chunks list received multiple times";
} else {
dirQueue_->setPreviouslyReceivedChunks(fileChunksInfoList);
fileChunksReceived_ = true;
}
}
// send ack for file chunks list
buf[0] = Protocol::ACK_CMD;
int64_t toWrite = 1;
int64_t written = socket->write(buf, toWrite);
if (toWrite != written) {
LOG(ERROR) << "Socket write error " << toWrite << " " << written;
threadStats.setErrorCode(SOCKET_WRITE_ERROR);
return CHECK_FOR_ABORT;
}
threadStats.addHeaderBytes(written);
return SEND_BLOCKS;
}
Sender::SenderState Sender::readReceiverCmd(ThreadData &data) {
VLOG(1) << "entered READ_RECEIVER_CMD state " << data.threadIndex_;
int port = ports_[data.threadIndex_];
TransferStats &threadStats = data.threadStats_;
char *buf = data.buf_;
int64_t numRead = data.socket_->read(buf, 1);
if (numRead != 1) {
LOG(ERROR) << "READ unexpected " << numRead;
threadStats.setErrorCode(SOCKET_READ_ERROR);
return CONNECT;
}
Protocol::CMD_MAGIC cmd = (Protocol::CMD_MAGIC)buf[0];
if (cmd == Protocol::ERR_CMD) {
return PROCESS_ERR_CMD;
}
if (cmd == Protocol::WAIT_CMD) {
return PROCESS_WAIT_CMD;
}
if (cmd == Protocol::DONE_CMD) {
return PROCESS_DONE_CMD;
}
if (cmd == Protocol::ABORT_CMD) {
return PROCESS_ABORT_CMD;
}
if (cmd == Protocol::LOCAL_CHECKPOINT_CMD) {
int checkpointLen = Protocol::getMaxLocalCheckpointLength(protocolVersion_);
int64_t toRead = checkpointLen - 1;
numRead = data.socket_->read(buf + 1, toRead);
if (numRead != toRead) {
LOG(ERROR) << "Could not read possible local checkpoint " << toRead << " "
<< numRead << " " << port;
threadStats.setErrorCode(SOCKET_READ_ERROR);
return CONNECT;
}
int64_t offset = 0;
std::vector<Checkpoint> checkpoints;
if (Protocol::decodeCheckpoints(protocolVersion_, buf, offset,
checkpointLen, checkpoints)) {
if (checkpoints.size() == 1 && checkpoints[0].port == port &&
checkpoints[0].numBlocks == 0 &&
checkpoints[0].lastBlockReceivedBytes == 0) {
// In a spurious local checkpoint, number of blocks and offset must both
// be zero
// Ignore the checkpoint
LOG(WARNING)
<< "Received valid but unexpected local checkpoint, ignoring "
<< port;
return READ_RECEIVER_CMD;
}
}
LOG(ERROR) << "Failed to verify spurious local checkpoint, port " << port;
threadStats.setErrorCode(PROTOCOL_ERROR);
return END;
}
LOG(ERROR) << "Read unexpected receiver cmd " << cmd << " port " << port;