std::unique_ptr SenderThread::connectToReceiver()

in SenderThread.cpp [35:106]


std::unique_ptr<IClientSocket> SenderThread::connectToReceiver(
    const int port, IAbortChecker const * /*abortChecker*/,
    ErrorCode &errCode) {
  auto startTime = Clock::now();
  int connectAttempts = 0;
  std::unique_ptr<IClientSocket> socket;
  const EncryptionParams &encryptionData =
      wdtParent_->transferRequest_.encryptionData;
  int64_t ivChangeInterval = wdtParent_->transferRequest_.ivChangeInterval;
  if (threadProtocolVersion_ <
      Protocol::PERIODIC_ENCRYPTION_IV_CHANGE_VERSION) {
    WTLOG(WARNING) << "Disabling periodic iv change for sender with version "
                   << threadProtocolVersion_;
    ivChangeInterval = 0;
  }

  if (wdtParent_->socketCreator_) {
    VLOG(3) << "Creating sender socket";
    socket = wdtParent_->socketCreator_->makeClientSocket(
        *threadCtx_, wdtParent_->getDestination(), port, encryptionData,
        ivChangeInterval, wdtParent_->transferRequest_.tls);
  } else {
    // socket creator not set, creating ClientSocket
    VLOG(3) << "Creating sender socket";
    socket = std::make_unique<ClientSocket>(*threadCtx_,
                                            wdtParent_->getDestination(), port,
                                            encryptionData, ivChangeInterval);
  }

  if (!socket) {
    errCode = ERROR;
    return nullptr;
  }

  double retryInterval = options_.sleep_millis;
  int maxRetries = options_.max_retries;
  if (maxRetries < 1) {
    WTLOG(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 (getThreadAbortCode() != OK) {
      errCode = ABORT;
      return nullptr;
    }
    if (i != maxRetries) {
      // sleep between attempts but not after the last
      WTVLOG(1) << "Sleeping after failed attempt " << i;
      /* sleep override */ usleep(retryInterval * 1000);
    }
  }
  double elapsedSecsConn = durationSeconds(Clock::now() - startTime);
  if (errCode != OK) {
    WTLOG(ERROR) << "Unable to connect to " << wdtParent_->getDestination()
                 << " " << port << " despite " << connectAttempts
                 << " retries in " << elapsedSecsConn << " seconds.";
    errCode = CONN_ERROR;
    return nullptr;
  }

  (connectAttempts > 1) ? WTLOG(WARNING) : WTLOG(INFO)
      << "Connection took " << connectAttempts << " attempt(s) and "
      << elapsedSecsConn << " seconds. port " << port;
  return socket;
}