LightNetwork.cpp 13.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

Y
Yu Yang 已提交
15
#include <fcntl.h>
Z
zhangjinchao01 已提交
16 17
#include <netdb.h>
#include <netinet/in.h>
18
#include <netinet/tcp.h>
Y
Yu Yang 已提交
19 20
#include <sys/socket.h>
#include <sys/types.h>
21
#include <chrono>
Z
zhangjinchao01 已提交
22 23 24

#include <arpa/inet.h>
#include <net/if.h>
Y
Yu Yang 已提交
25
#include <sys/ioctl.h>
Z
zhangjinchao01 已提交
26
#include <sstream>
L
liaogang 已提交
27

Z
zhangjinchao01 已提交
28 29
#include "LightNetwork.h"
#include "RDMANetwork.h"
Y
Yu Yang 已提交
30 31
#include "paddle/utils/StringUtil.h"
#include "paddle/utils/Util.h"
Z
zhangjinchao01 已提交
32 33

/// quick ack can reduce the latency of small message
34 35 36 37
DEFINE_bool(small_messages,
            false,
            "if message size is small, recommend set it True to enable quick "
            "ack and no delay");
Z
zhangjinchao01 已提交
38 39 40 41

/// reasonable sock_send_buf_size can control the traffic injected into switch
/// network. Injecting too many data into traffic could cause packets loss which
/// cause long latency and degrade the efficiency of communication.
42 43 44 45
DEFINE_int32(sock_send_buf_size,
             1024 * 1024 * 40,
             "restrict sock send buff size, can reduce network congestion if "
             "set carefully");
Z
zhangjinchao01 已提交
46 47

/// reasonable size can hold bursted packets and reduce packets loss
48 49 50
DEFINE_int32(sock_recv_buf_size,
             1024 * 1024 * 40,
             "restrict sock recv buff size");
Z
zhangjinchao01 已提交
51

武毅 已提交
52 53 54 55 56
/// reasonable sock_listen_queue_size can control maximum pending connections.
DEFINE_int32(sock_listen_queue_size,
             1024,
             "listen queue size when pserver listen a TCP port");

Z
zhangjinchao01 已提交
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
namespace paddle {

/**
 * @brief get ip address from interface name
 *
 * @param[in] device device interface name
 */
std::string getIpAddr(std::string &device) {
  int sock;
  struct sockaddr_in sin;
  struct ifreq ifr;

  sock = socket(AF_INET, SOCK_DGRAM, 0);
  CHECK(sock >= 0) << "Create socket error.";

  strncpy(ifr.ifr_name, device.c_str(), IFNAMSIZ);
  ifr.ifr_name[IFNAMSIZ - 1] = 0;

  CHECK_GE(ioctl(sock, SIOCGIFADDR, &ifr), 0);
  memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
  close(sock);
  return std::string(inet_ntoa(sin.sin_addr));
}

/**
 * @brief set sock option
 *
 * @param[in] sockfd sock file descriptor
 *
 * @note adjust some default sock option for better performance
 */
void setOption(int sockfd) {
89
#if !defined(__APPLE__) && !defined(__OSX__)
Z
zhangjinchao01 已提交
90 91 92 93 94 95 96 97
  int sendSize = FLAGS_sock_send_buf_size;
  int recvSize = FLAGS_sock_recv_buf_size;
  CHECK_GE(
      setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recvSize, sizeof(recvSize)),
      0);
  CHECK_GE(
      setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sendSize, sizeof(sendSize)),
      0);
98 99
#endif

Z
zhangjinchao01 已提交
100 101 102 103 104
  if (FLAGS_small_messages) {
    int optval = 1;
    CHECK_GE(
        setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval)),
        0);
L
liaogang 已提交
105
#ifdef TCP_QUICKACK
Z
zhangjinchao01 已提交
106 107 108 109
    optval = 1;
    CHECK_GE(
        setsockopt(sockfd, IPPROTO_TCP, TCP_QUICKACK, &optval, sizeof(optval)),
        0);
L
liaogang 已提交
110
#endif
Z
zhangjinchao01 已提交
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
  }
  int reuse = 1;
  CHECK_GE(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)),
           0);
}

/**
 * @brief class constructor for SocketServer
 * @param[in] addr sock bind address
 * @param[in] port sock bind port
 * @param[in] rdmaCpu rdma sock bind cpu core
 *
 * @note start one socket server which hosts parameter server process.
 *       rdmaCpu is passed to rdma deamon for better performance, and
 *       start tcp socket instead of rdma socket if rdmaCpu is equal
 *       to -1. Each trainer process starts one connection to one socket
 *       server, and use --ports_num to build more connections to harness
 *       fat communication channel if necessary.
 *       each connection is controlled by single thread with blocking
 *       read and write.
 */
SocketServer::SocketServer(const std::string &addr, int port, int rdmaCpu)
    : port_(port), addr_(addr), stopping_(false) {
  if (rdmaCpu == -1) {
    tcpRdma_ = F_TCP;
    socket_ = 0;
武毅 已提交
137
    maxPendingConnections_ = FLAGS_sock_listen_queue_size;
Z
zhangjinchao01 已提交
138 139 140 141 142 143 144 145 146 147 148
  } else {
    tcpRdma_ = F_RDMA;
    rdmaCpu_ = rdmaCpu;
    rdmaSocket_ = 0;

    std::stringstream ss;
    ss << port;
    rdmaUri_ = "rdma://" + addr + ":" + ss.str();
  }

  /// trigger to initialize RDMA lib
Y
Yu Yang 已提交
149
  CHECK(RdmaClientDaemons::get()) << "initilizate RDMA failed\n";
Z
zhangjinchao01 已提交
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
}

SocketServer::~SocketServer() {
  stopping_ = true;
  /// trigger accept thread to stop
  {
    SocketClient trigger(addr_.empty() ? "127.0.0.1" : addr_, port_, tcpRdma_);
  }
  this->join();
}

/**
 * @brief start one tcp server which hosts parameter server
 *
 * @note do tcp socket bind and listen. it will spawn one thread
 *       for each connection
 */
void SocketServer::tcpServer() {
  int newsockfd;
  socklen_t clilen;
  struct sockaddr_in serv_addr, cli_addr;
  struct hostent *server;

  /// First call to socket() function
  socket_ = socket(AF_INET, SOCK_STREAM, 0);
Y
Yu Yang 已提交
175
  CHECK(socket_ >= 0) << "ERROR opening socket";
Z
zhangjinchao01 已提交
176 177 178 179 180 181 182

  /// Initialize socket structure
  bzero((char *)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(port_);
  if (!addr_.empty()) {
    server = gethostbyname(addr_.c_str());
Y
Yu Yang 已提交
183
    CHECK(server) << "ERROR, no such host: " << addr_;
184 185
    bcopy((char *)server->h_addr,
          (char *)&serv_addr.sin_addr.s_addr,
Z
zhangjinchao01 已提交
186 187 188 189 190 191 192 193
          server->h_length);
  } else {
    serv_addr.sin_addr.s_addr = INADDR_ANY;
  }

  setOption(socket_);

  /// Now bind the host address using bind() call.
Y
Yu Yang 已提交
194
  CHECK(bind(socket_, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) >= 0)
Z
zhangjinchao01 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207
      << "ERROR on binding " << addr_;

  /// Now start listening for the clients, here process will
  /// go in sleep mode and will wait for the incoming connection
  listen(socket_, maxPendingConnections_);
  clilen = sizeof(cli_addr);

  while (true) {
    /// Accept actual connection from the client
    newsockfd = accept(socket_, (struct sockaddr *)&cli_addr, &clilen);
    if (stopping_) {
      break;
    }
Y
Yu Yang 已提交
208
    CHECK(newsockfd >= 0) << "ERROR on accept";
Z
zhangjinchao01 已提交
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
    constexpr int kPeerNameLen = 128;
    char peerName[kPeerNameLen];
    CHECK(inet_ntop(AF_INET, &cli_addr.sin_addr, peerName, kPeerNameLen));

    SocketWorker *worker =
        new SocketWorker(createChannel(newsockfd, std::string(peerName)), this);
    worker->start();
    worker->detach();
  }
  close(socket_);
  LOG(INFO) << "pserver accept thread finish, addr=" << addr_
            << " port=" << port_;
}

/**
 * @brief start one rdma server which hosts parameter server
 *
 * @note do rdma bind and listen, which calling self-defined socket
 *       like rdma library. it will spawn one thread for each connection
 */
void SocketServer::rdmaServer() {
  struct sxi_sock *newsock;

  /// First call to socket() function
  rdmaSocket_ = rdma::ssocket(rdmaCpu_);
Y
Yu Yang 已提交
234
  CHECK(rdmaSocket_) << "ERROR opening RDMA socket";
Z
zhangjinchao01 已提交
235

Y
Yu Yang 已提交
236
  CHECK(rdma::bind(rdmaSocket_, rdmaUri_.c_str()) == 0)
Z
zhangjinchao01 已提交
237 238 239 240
      << "ERROR bind RDMA socket";

  /// Now start listening for the clients, here process will
  /// go in sleep mode and will wait for the incoming connection
Y
Yu Yang 已提交
241
  CHECK(rdma::listen(rdmaSocket_) == 0) << "ERROR listen RDMA socket";
Z
zhangjinchao01 已提交
242 243 244 245 246 247 248

  while (true) {
    /// Accept actual connection from the client
    newsock = rdma::accept(rdmaSocket_);
    if (stopping_) {
      break;
    }
Y
Yu Yang 已提交
249
    CHECK(newsock) << "ERROR on accept";
Z
zhangjinchao01 已提交
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

    constexpr int kPeerNameLen = 128;
    char peerName[kPeerNameLen];

    struct sockaddr_in *saddr = rdma::getSourceAddress(newsock);
    CHECK(inet_ntop(AF_INET, &saddr->sin_addr, peerName, kPeerNameLen));

    SocketWorker *worker =
        new SocketWorker(createChannel(newsock, std::string(peerName)), this);
    worker->start();
    worker->detach();
  }
  rdma::close(rdmaSocket_);
  LOG(INFO) << "pserver accept thread finish, rdma uri=" << rdmaUri_;
}

/**
 * @brief start a socket server
 *
 * @note framework for starting socket server
 */
void SocketServer::run() {
  if (tcpRdma_ == F_TCP) {
    LOG(INFO) << "tcp server start ";
    tcpServer();
  } else if (tcpRdma_ == F_RDMA) {
    LOG(INFO) << "rdma server start ";
    rdmaServer();
  }
}

/**
 * @brief class constructor for rdma client deamons
 *
 * @note  automatically start several client deamons for better performance
 */
std::unique_ptr<RdmaClientDaemons> RdmaClientDaemons::daemons_ = nullptr;
std::once_flag RdmaClientDaemons::initDataFlag_;

RdmaClientDaemons::RdmaClientDaemons() {
  if (FLAGS_rdma_tcp == "rdma") {
    rdma::init();

    struct sxi_socket *socket;
    onlineCpus_ = rdma::numCpus();
    for (auto i = 0; i < onlineCpus_; i++) {
      socket = rdma::csocket(i);
Y
Yu Yang 已提交
297
      CHECK(socket) << "ERROR open client socket daemon";
Z
zhangjinchao01 已提交
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

      rdmaClientSocket_.push_back(socket);
    }
    LOG(INFO) << "RDMA client daemons started, onlineCpus_:" << onlineCpus_;
    /// round robin scheduler for new connection
    curCpu_ = 0;
    /// wait daemons to start completely.
    sleep(2);
  }
}

RdmaClientDaemons::~RdmaClientDaemons() {
  if (FLAGS_rdma_tcp == "rdma") {
    for (auto i = 0; i < onlineCpus_; i++) {
      rdma::close(rdmaClientSocket_[i]);
    }
    LOG(INFO) << "RDMA client daemons is destoryed, onlineCpus_ "
              << onlineCpus_;
  }
}

/**
 * @brief worker thread main context
 *
 * @note  each connection from client(trainer) is controlled by single worker
 *        thread, which is for handling all parameter server requests
 */
void SocketWorker::run() {
  LOG(INFO) << "worker started, peer = " << channel_->getPeerName();

  std::vector<iovec> inputIovs;

  while (true) {
    std::unique_ptr<MsgReader> msgReader = channel_->readMessage();
    if (!msgReader) {
      break;
    }

    auto callback = [this](const std::vector<iovec> &outputIovs) {
      channel_->writeMessage(outputIovs);
    };

    server_->handleRequest(std::move(msgReader), callback);
  }

  LOG(INFO) << "worker begin to finish, peer = " << channel_->getPeerName();
  delete this;
}

/**
 * @brief start one tcp connection to tcp server
 * @param[in] serverAddr  tcp server ip
 * @param[in] serverPort  tcp server port
 *
 * @note each object contains one channel which accept byte stream
 */
void SocketClient::TcpClient(const std::string &serverAddr, int serverPort) {
  struct sockaddr_in serv_addr;
L
liaogang 已提交
356 357
  struct hostent *server;

358
  int errRet;  // temp for gethostbyname_r
Z
zhangjinchao01 已提交
359 360 361

  /// Create a socket point
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
Y
Yu Yang 已提交
362
  CHECK(sockfd >= 0) << "ERROR opening socket";
L
liaogang 已提交
363 364

#if defined(__OSX__) || defined(__APPLE__)
365 366 367 368
  server = getipnodebyname(serverAddr.c_str(), AF_INET, AI_DEFAULT, &errRet);
  CHECK_NE(HOST_NOT_FOUND, errRet) << "ERROR, no such host: " << serverAddr
                                   << " ret = " << errRet;
  CHECK(server) << "getipnodebyname error!";
L
liaogang 已提交
369
#else
370 371 372 373 374 375 376 377
  struct hostent hostinfo;
  char buf[1024];  // temp for gethostbyname_r
  CHECK_EQ(
      0,
      gethostbyname_r(
          serverAddr.c_str(), &hostinfo, buf, sizeof(buf), &server, &errRet))
      << "ERROR, no such host: " << serverAddr << " ret = " << errRet;
  CHECK(server) << "gethostbyname_r error!";
L
liaogang 已提交
378
#endif
Z
zhangjinchao01 已提交
379 380 381

  bzero((char *)&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
382 383
  bcopy((char *)server->h_addr,
        (char *)&serv_addr.sin_addr.s_addr,
Z
zhangjinchao01 已提交
384 385 386 387 388 389
        server->h_length);
  serv_addr.sin_port = htons(serverPort);

  setOption(sockfd);

  /// Now connect to the server
H
Helin Wang 已提交
390
  int retry_count = 0;
391
  do {
H
Helin Wang 已提交
392 393 394 395 396
    if (connect(sockfd, (sockaddr *)&serv_addr, sizeof(serv_addr)) == 0) {
      break;
    }

    if (errno == ECONNREFUSED) {
397
      LOG(WARNING) << "connection refused by pserver, try again!";
H
Helin Wang 已提交
398
      if (retry_count++ >= 7) {
399 400 401 402
        LOG(FATAL) << "connection refused by pserver, maybe pserver failed!";
      }
      std::this_thread::sleep_for(std::chrono::seconds(1));
    } else {
Y
Yu Yang 已提交
403 404
      CHECK(errno != 0) << "ERROR connecting to " << serverAddr << ":"
                        << serverPort << "errorno: " << errno;
405
    }
H
Helin Wang 已提交
406
  } while (errno == ECONNREFUSED);
Z
zhangjinchao01 已提交
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

  channel_.reset(new SocketChannel(sockfd, serverAddr));
  tcpRdma_ = F_TCP;
}

/**
 * @brief start one RDMA connection to rdma server
 * @param[in] serverAddr  rdma server ip
 * @param[in] serverPort  rdma server port
 *
 * @note  each object contains one channel which accept byte stream
 *        for rdma, low level sock also provide byte stream api.
 */
void SocketClient::RdmaClient(const std::string &serverAddr, int serverPort) {
  struct sxi_sock *sock;

  std::stringstream ss;
  ss << serverPort;

  std::string rdmaUri = "rdma://" + serverAddr + ":" + ss.str();

  RdmaClientDaemons *daemons = RdmaClientDaemons::daemons_->get();
  socketDaemon_ = daemons->selectDaemon();

  /// connect to server with socket daemon
  sock = rdma::connect(socketDaemon_, rdmaUri.c_str());
Y
Yu Yang 已提交
433
  CHECK(sock) << "ERROR connect to server" << rdmaUri;
Z
zhangjinchao01 已提交
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

  std::vector<std::string> seg;
  str::split(rdmaUri, '/', &seg);
  std::string server = seg.at(seg.size() - 1);
  channel_.reset(new SocketChannel(sock, server));
  tcpRdma_ = F_RDMA;
}

/**
 * @brief class constructor
 * @param[in] serverAddr pserver ip address
 * @param[in] serverPort pserver port
 * @param[in] ChannelType F_TCP or F_RDMA
 *
 * @note  responsible for building one connection to specified pserver port
 */
450 451
SocketClient::SocketClient(const std::string &serverAddr,
                           int serverPort,
Z
zhangjinchao01 已提交
452 453 454 455 456 457 458 459
                           enum ChannelType channelType) {
  if (channelType == F_RDMA)
    RdmaClient(serverAddr, serverPort);
  else
    TcpClient(serverAddr, serverPort);
}

}  // namespace paddle